HTTPClient和URLConnection核心区别分析
来源:互联网 发布:单片机光耦驱动继电器 编辑:程序博客网 时间:2024/05/21 06:43
在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。
其次:HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,
HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。
HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收响应,以及管理HTTP连接。
使用HttpClient发送请求、接收响应很简单,只要如下几步即可:
1.创建HttpClient对象。
2.如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3.如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4.调用HttpClient对象的execute(HttpUriRequest request)发送请求,执行该方法返回一个HttpResponse。
5.调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
具体对比如下:HTTPClient
String url = "http://192.168.1.100:8080";
public HttpClientServer(){ }
public String doGet(String username,String password){
String getUrl = urlAddress + "?username="+username+"&password="+password;
HttpGet httpGet = new HttpGet(getUrl);
HttpParams hp = httpGet.getParams();
hp.getParameter("true");
//httpGet.setp
HttpClient hc = new DefaultHttpClient();
try {
HttpResponse ht = hc.execute(httpGet);
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity he = ht.getEntity();
InputStream is = he.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while((readLine =br.readLine()) != null){
//response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
//String str = EntityUtils.toString(he);
return response;
}else{
return "error";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return "exception";
} catch (IOException e) {
e.printStackTrace();
return "exception";
}
}
public String doPost(String username,String password){
//String getUrl = urlAddress + "?username="+username+"&password="+password;
HttpPost httpPost = new HttpPost(urlAddress);
List params = new ArrayList();
NameValuePair pair1 = new BasicNameValuePair("username", username);
NameValuePair pair2 = new BasicNameValuePair("password", password);
params.add(pair1);
params.add(pair2);
HttpEntity he;
try {
he = new UrlEncodedFormEntity(params, "gbk");
httpPost.setEntity(he);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
HttpClient hc = new DefaultHttpClient();
try {
HttpResponse ht = hc.execute(httpPost);
//连接成功
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity het = ht.getEntity();
InputStream is = het.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while((readLine =br.readLine()) != null){
//response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
//String str = EntityUtils.toString(he);
return response;
}else{
return "error";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return "exception";
} catch (IOException e) {
e.printStackTrace();
return "exception";
}
}
HttpURLConnection:
String url = "http://192.168.1.100:8080";
URL url;
HttpURLConnection uRLConnection;
public UrlConnectionToServer(){ }
//向服务器发送get请求
public String doGet(String username,String password){
String getUrl = urlAddress + "?username="+username+"&password="+password;
try {
url = new URL(getUrl);
uRLConnection = (HttpURLConnection)url.openConnection();
InputStream is = uRLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while((readLine =br.readLine()) != null){
//response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
uRLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
returnnull;
} catch (IOException e) {
e.printStackTrace();
returnnull;
}
}
//向服务器发送post请求
public String doPost(String username,String password){
try {
url = new URL(urlAddress);
uRLConnection = (HttpURLConnection)url.openConnection();
uRLConnection.setDoInput(true);
uRLConnection.setDoOutput(true);
uRLConnection.setRequestMethod("POST");
uRLConnection.setUseCaches(false);
uRLConnection.setInstanceFollowRedirects(false);
uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
uRLConnection.connect();
DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
String content = "username="+username+"&password="+password;
out.writeBytes(content);
out.flush();
out.close();
InputStream is = uRLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while((readLine =br.readLine()) != null){
//response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
uRLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
returnnull;
} catch (IOException e) {
e.printStackTrace();
returnnull;
}
}
客户端操作:
String url = "http://192.168.1.102:8080";
String body =
getContent(urlAddress);
JSONArray array = new JSONArray(body);
for(int i=0;i<array.length();i++)
{
obj = array.getJSONObject(i);
sb.append("用户名:").append(obj.getString("username")).append("\t");
sb.append("密码:").append(obj.getString("password")).append("\n");
HashMap<String, Object> map = new HashMap<String, Object>();
try {
userName = obj.getString("username");
passWord = obj.getString("password");
} catch (JSONException e) {
e.printStackTrace();
}
map.put("username", userName);
map.put("password", passWord);
listItem.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
if(sb!=null)
{
showResult.setText("用户名和密码信息:");
showResult.setTextSize(20);
} else
extracted();
//设置adapter
SimpleAdapter simple = new SimpleAdapter(this,listItem,
android.R.layout.simple_list_item_2,
new String[]{"username","password"},
newint[]{android.R.id.text1,android.R.id.text2});
listResult.setAdapter(simple);
listResult.setOnItemClickListener(new OnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int positionId = (int) (id+1);
Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show();
}
});
}
privatevoid extracted() {
showResult.setText("没有有效的数据!");
}
//和服务器连接
private String getContent(String url)throws Exception{
StringBuilder sb = new StringBuilder();
HttpClient client =new DefaultHttpClient();
HttpParams httpParams =client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpResponse response = client.execute(new HttpGet(url));
HttpEntity entity =response.getEntity();
if(entity !=null){
BufferedReader reader = new BufferedReader(new InputStreamReader
(entity.getContent(),"UTF-8"),8192);
String line =null;
while ((line= reader.readLine())!=null){
sb.append(line +"\n");
}
reader.close();
}
return sb.toString();
}
------------------------------------------------------
private void HttpPostData() {
try {
HttpClient httpclient = new DefaultHttpClient();
String uri = "http://www.yourweb.com";
HttpPost httppost = new HttpPost(uri);
//添加http头信息
httppost.addHeader("Authorization", "your token"); //认证token
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("User-Agent", "imgfornote");
//http post的json数据格式: {"name": "your name","parentId": "id_of_parent"}
JSONObject obj = new JSONObject();
obj.put("name", "your name");
obj.put("parentId", "your parentid");
httppost.setEntity(new StringEntity(obj.toString()));
HttpResponse response;
response = httpclient.execute(httppost);
//检验状态码,如果成功接收数据
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
String rev = EntityUtils.toString(response.getEntity());//返回json格式: {"id": "27JpL~j4vsL0LX00E00005","version": "abc"}
obj = new JSONObject(rev);
String id = obj.getString("id");
String version = obj.getString("version");
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (Exception e) {
}
}
----------------------------------------
http://www.cnblogs.com/smyhvae/p/4006009.html
private class httpPost extends AsyncTask<String, Void, JSONObject> { protected JSONObject doInBackground(String... args) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, 10000); HttpConnectionParams.setSoTimeout(myParams, 10000); String url = args[0]; String json=args[1]; JSONObject JSONResponse = null; InputStream contentStream = null; String resultString = ""; try { HttpPost httppost = new HttpPost(url); httppost.setHeader("Content-Type", "application/json"); httppost.setHeader("Accept", "application/json"); StringEntity se = new StringEntity(json); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppost.setEntity(se); for (int i=0;i<httppost.getAllHeaders().length;i++) { Log.v("set header", httppost.getAllHeaders()[i].getValue()); } HttpResponse response = httpclient.execute(httppost); // Do some checks to make sure that the request was processed properly Header[] headers = response.getAllHeaders(); HttpEntity entity = response.getEntity(); contentStream = entity.getContent(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } contentStream.close(); resultString = sb.toString(); }catch(Exception e){ e.printStackTrace(); } Log.v("li", resultString); return new JSONObject(); }}
- HTTPClient和URLConnection核心区别分析
- HTTPClient和URLConnection核心区别分析
- HTTPClient和URLConnection核心区别分析
- httpclient和urlconnection的区别
- android httpClient和URLConnection的区别
- android 中HttpClient和URLConnection的区别
- httpclient和urlconnection比较
- Java.net.URLConnection和Apache HTTPClient的主要区别对比
- Java.net.URLConnection和Apache HTTPClient的主要区别对比
- URLConnection和HTTPClient的比较
- URLConnection和HTTPClient的比较
- URLConnection和HttpClient使用入门
- URLConnection和HTTPClient的比较
- URLConnection和HTTPClient的比较
- URLConnection和HTTPClient的比较
- HttpClient和URLConnection的应用
- 通过httpclient和urlconnection下载网络文件
- ======URLConnection 和 HttpClient的区别======
- 笔记:Linux vi编辑器
- 黑马程序员—常用String类和StringBuffer
- FZOJ2110: Star
- HDOJ 4650: Minimum Average Weight Path
- JavaWeb的MyEclipse快速开发技巧:搜索
- HTTPClient和URLConnection核心区别分析
- linux中用户、用户组与文件权限
- linux系统移植要点
- 《JAVA与模式》学习计划
- AndroidManifest.xml配置文件各个知识点详解
- Seven Databases in Seven Weeks(七周七数据库)——PostgreSQL
- UVA 11039 - Building designing 水题哇~
- 源代码编译lamp环境
- 如何分配内存 内存碎片处理技术