歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中的HTTP通信

Java中的HTTP通信

日期:2017/3/1 9:12:52   编辑:Linux編程

在Android中,HTTP通信可以用Volley,在Java中不能使用Volley,只能使用DefaultHttpClient,HttpPost和HttpResponse。

/*
* 向服務器發送數據,並接受返回的數據
*/
public static String send2Server(String url, List <NameValuePair> params){
String res = null;

// 建立HTTPPost連接
HttpPost httpRequest = new HttpPost(url);
try
{
// 發出HTTP Request
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 取得HTTP Response
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
res = EntityUtils.toString(httpResponse.getEntity());
}
catch (Exception e){
e.printStackTrace();
}

return res;
}

Copyright © Linux教程網 All Rights Reserved