HttpClient與HttpURLConnection的提交資料
阿新 • • 發佈:2018-11-16
使用HttpClient提交資料(get)
//get提交
public void click1(View view) throws Exception{
final String username = et_text1.getText().toString().trim();
final String password = et_text2.getText().toString().trim();
if (TextUtils.isEmpty(username)&&TextUtils.isEmpty(password)) {
Toast.makeText(this , "使用者名稱和密碼不能為空", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
try {
String path = "http://192.168.17.12:8080/http/loginServlet";
HttpClient client = new DefaultHttpClient();
//http://localhost:8080/http/loginServlet?username=123&password=111
HttpGet request = new HttpGet(path+"?username="+URLEncoder.encode(username)+"&password="+password);
HttpResponse response = client.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (200==statusCode) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
String data = StreamUtils.stream2string(inputStream);
handler.obtainMessage(RESULT_OK, data).sendToTarget();
}else {
handler.obtainMessage(RESULT_CANCELED, "handler傳送資訊失敗!").sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
使用HttpClient提交資料(post)
//post提交
public void click2(View view){
final String username = et_text1.getText().toString().trim();
final String password = et_text2.getText().toString().trim();
if (TextUtils.isEmpty(username)&&TextUtils.isEmpty(password)) {
Toast.makeText(this, "使用者名稱和密碼不能為空", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
try {
String path = "http://192.168.17.12:8080/http/loginServlet";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(path);
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
HttpEntity entity = new UrlEncodedFormEntity(parameters );
request.setEntity(entity );
HttpResponse response = client.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (200==statusCode) {
HttpEntity entity2 = response.getEntity();
InputStream content = entity2.getContent();
final String data = StreamUtils.stream2string(content);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,data+"提交成功", Toast.LENGTH_SHORT).show();
}
});
}else {
HttpEntity entity2 = response.getEntity();
InputStream content = entity2.getContent();
final String data = StreamUtils.stream2string(content);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,data+"提交失敗!!!", Toast.LENGTH_SHORT).show();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public class StreamUtils {
public static String stream2string(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len=-1;
byte[] buffer = new byte[1024];
while((len=is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
bos.close();
return bos.toString();
}
}
使用HttpURLConnection提交資料(get)
//get提交
public void click1(View view) throws Exception{
final String username = et_text1.getText().toString().trim();
final String password = et_text2.getText().toString().trim();
if (TextUtils.isEmpty(username)&&TextUtils.isEmpty(password)) {
Toast.makeText(this, "使用者名稱和密碼不能為空", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
try {
//http://localhost:8080/http/loginServlet?username=123&password=123
String path = "http://192.168.37.2:8080/http/loginServlet?username="+URLEncoder.encode(username)+"&password="+password;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT2);
conn.connect();
int responseCode = conn.getResponseCode();
if (200==responseCode) {
InputStream is = conn.getInputStream();
String data = StreamUtils.stream2string(is);
handler.obtainMessage(RESULT_OK, data).sendToTarget();
}else {
handler.obtainMessage(RESULT_CANCELED, "handler傳送資訊失敗!").sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
使用HttpURLConnection提交資料(post)
//post提交
public void click2(View view){
final String username = et_text1.getText().toString().trim();
final String password = et_text2.getText().toString().trim();
if (TextUtils.isEmpty(username)&&TextUtils.isEmpty(password)) {
Toast.makeText(this, "使用者名稱和密碼不能為空", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
try {
String path = "http://192.168.37.2:8080/http/loginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT2);
conn.connect();
//開啟一個流給伺服器提交資料
OutputStream os = conn.getOutputStream();
String param = "username="+URLEncoder.encode(username)+"&password="+password;
os.write(param.getBytes());
int responseCode = conn.getResponseCode();
if (200==responseCode) {
InputStream is = conn.getInputStream();
String data = StreamUtils.stream2string(is);
handler.obtainMessage(RESULT_OK, data).sendToTarget();
}else {
handler.obtainMessage(RESULT_CANCELED, "handler傳送資訊失敗!").sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
HttpClient與HttpURLConnection區別
1、HttpClient是apache的開源實現,而HttpUrlConnection是安卓標準實現,安卓SDK雖然集成了HttpClient,但官方支援的卻是HttpUrlConnection;
2、HttpUrlConnection直接支援GZIP壓縮;HttpClient也支援,但要自己寫程式碼處理;
3、HttpUrlConnection直接在系統層面做了快取策略處理,加快重複請求的速度。