HttpUrlConnection和HttpClient和android-async-http框架的GET和POST請求
1.HttpUrlConnection
public class NetUtil {
public static String doGet(String username,String password) {
try {
String data = "username=" + username + "&password=" + password;
URL url = new URL("http://115.192.188.146:9090/Android//servlet/LoginServlet?"+data);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
conn.setReadTimeout(5000);
if(conn.getResponseCode()==200){
InputStream is = conn.getInputStream();
String result = getStringFromInputStream(is);
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String doPost(String username,String password) {
try {
// post請求的引數
String data = "username=" + username + "&password=" + password;
URL url = new URL("http://115.192.188.146:9090/Android//servlet/LoginServlet");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(3000);
conn.setReadTimeout(5000);
conn.setDoOutput(true);//預設情況下, 系統不允許向伺服器輸出內容
// 獲得一個輸出流, 用於向伺服器寫資料, 預設情況下, 系統不允許向伺服器輸出內容 所以要設定conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());//將請求的資料寫入輸出流裡
os.flush();
os.close();
if(conn.getResponseCode()==200){
InputStream is = conn.getInputStream();
String result = getStringFromInputStream(is);
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
try {
if(is!=null){
int len = 0;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
String result = baos.toString();
is.close();
baos.close();
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
2.HttpClient
public class NetUtil {
public static String doHttpClientGet(String username,String password) {
HttpClient client = null;
try {
String data = "username=" + username + "&password=" + password;
client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://10.0.2.2:9090/Android//servlet/LoginServlet?"+data);
HttpResponse response = client.execute(get);
if(response.getStatusLine().getStatusCode()==200){
InputStream is = response.getEntity().getContent();
return getStringFromInputStream(is);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client!=null){ //關閉連線
client.getConnectionManager().shutdown();
}
}
return null;
}
public static String doHttpClientPost(String username,String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:9090/Android//servlet/LoginServlet");
//設定請求的引數
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
//把post請求的引數包裝了一層
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
//設定引數
post.setEntity(entity);
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode()==200){
InputStream is = response.getEntity().getContent();
return getStringFromInputStream(is);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(client!=null){
client.getConnectionManager().shutdown();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
try {
if(is!=null){
int len = 0;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
String result = baos.toString();
is.close();
baos.close();
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3.android-async-http
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
public void loginGET(View view){
String username = et_username.getText().toString();
String password = et_password.getText().toString();
String data = "username=" + username + "&password=" + password;
String url = "http://10.0.2.2:9090/Android//servlet/LoginServlet?"+data;
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new MyResponseHandler());//get請求
}
public void loginPOST(View view){
String username = et_username.getText().toString();
String password = et_password.getText().toString();
String url = "http://10.0.2.2:9090/Android//servlet/LoginServlet";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post(url, params , new MyResponseHandler());//post請求
}
private class MyResponseHandler extends AsyncHttpResponseHandler{
//請求成功時呼叫
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//這個回撥方法是在主執行緒執行的,所以在這個方法裡可以直接操作UI元件
Toast.makeText(getApplicationContext(), "成功:"+statusCode+" body--->"+new String(responseBody), Toast.LENGTH_SHORT).show();
}
//請求失敗時呼叫
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(), "失敗:"+statusCode, Toast.LENGTH_SHORT).show();
}
}
}
相關文章
- Android Http請求框架一:Get 和 Post 請求AndroidHTTP框架
- Get和Post請求詳解
- java apache commons HttpClient傳送get和post請求的學習整理JavaApacheHTTPclient
- get和post請求的區別(面試)面試
- java傳送GET和post請求Java
- PHP傳送POST和GET請求PHP
- $.post 和 $.get 設定同步和非同步請求非同步
- AJAX的POST和GET請求的區別
- http請求之get和post的區別HTTP
- JAVA中Get和Post請求的區別Java
- HttpURLConnection和HttpClient的使用HTTPclient
- http請求中get和post方法的區別HTTP
- HTTP協議GET和POST請求的區別HTTP協議
- AJAX的get和post請求原生編寫方法
- HTTP協議中請求方法的Get和PostHTTP協議
- 優雅地使用GET和POST請求方法
- 使用fidder進行post和get請求
- 專案一(一) HttpClient中的POST請求和GET請求HTTPclient
- GET和POST兩種基本請求方法的區別
- python3 實現 get 和 post 請求Python
- cURL實現傳送Get和Post請求(PHP)PHP
- GET和POST方式請求API介面資料返回API
- 原生js實現Ajax請求,包含get和postJS
- PHP中使用cURL實現Get和Post請求PHP
- ajax 請求的時候 get 和 post 方式的區別?
- node.js的express模組實現GET和POST請求Node.jsExpress
- 淺談HTTP中GET和POST請求方式的區別HTTP
- Go語言開發傳送Get和Post請求Go
- HttpURLConnection 實戰Get/Post 請求並且儲存PDF檔案HTTP
- nodejs關於get和post請求程式碼例項NodeJS
- Servlet中request請求Get和Post方法以及亂碼解決Servlet
- Golang:使用go-resty/resty傳送http請求get和postGolangRESTHTTP
- 使用HttpClient傳送GET請求HTTPclient
- OKHttp原始碼學習--HttpURLConnection HttpClient OKHttp Get and post Demo用法對比HTTP原始碼client
- get請求和post請求的區別
- iOS 同步請求 非同步請求 GET請求 POST請求iOS非同步
- node 使用get和post向後臺請求資料的使用方式對比
- GET和POST的區別?