httpurlconnection 和 httpclient 用哪个

 我来答
就烦条0o
2016-06-18 · 知道合伙人软件行家
就烦条0o
知道合伙人软件行家
采纳数:33315 获赞数:46492
从事多年系统运维,喜欢编写各种小程序和脚本。

向TA提问 私信TA
展开全部
1.概念

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP
协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP
协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。

除此之外,在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持
HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。

2.区别

HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,

HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。

3.案例

HttpURLConnection

String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do";
URL url;
HttpURLConnection uRLConnection;
publicUrlConnectionToServer(){

}//向服务器发送get请求
publicString doGet(String username,String password){
String getUrl = urlAddress + "?username="+username+"&password="+password;
try{
url =newURL(getUrl);
uRLConnection = (HttpURLConnection)url.openConnection();
InputStream is = uRLConnection.getInputStream();
BufferedReader br =newBufferedReader(newInputStreamReader(is));
String response = "";
String readLine =null;
while((readLine =br.readLine()) !=null){
//response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
uRLConnection.disconnect();
returnresponse;
}catch(MalformedURLException e) {
e.printStackTrace();
returnnull;
}catch(IOException e) {
e.printStackTrace();
returnnull;
}
}
//向服务器发送post请求
publicString doPost(String username,String password){
try{
url =newURL(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 =newDataOutputStream(uRLConnection.getOutputStream());
String content = "username="+username+"&password="+password;
out.writeBytes(content);
out.flush();
out.close();

InputStream is = uRLConnection.getInputStream();
BufferedReader br =newBufferedReader(newInputStreamReader(is));
String response = "";
String readLine =null;
while((readLine =br.readLine()) !=null){
//response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
uRLConnection.disconnect();
returnresponse;
}catch(MalformedURLException e) {
e.printStackTrace();
returnnull;
}catch(IOException e) {
e.printStackTrace();
returnnull;
}
}

HTTPClient

String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do";
publicHttpClientServer(){

}

publicString doGet(String username,String password){
String getUrl = urlAddress + "?username="+username+"&password="+password;
HttpGet httpGet =newHttpGet(getUrl);
HttpParams hp = httpGet.getParams();
hp.getParameter("true");
//hp.
//httpGet.setp
HttpClient hc =newDefaultHttpClient();
try{
HttpResponse ht = hc.execute(httpGet);
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity he = ht.getEntity();
InputStream is = he.getContent();
BufferedReader br =newBufferedReader(newInputStreamReader(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);
System.out.println("========="+response);
returnresponse;
}else{
return"error";
}
}catch(ClientProtocolException e) {
//TODO Auto-generated catch block
e.printStackTrace();
return"exception";
}catch(IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
return"exception";
}
}

publicString doPost(String username,String password){
//String getUrl = urlAddress + "?username="+username+"&password="+password;
HttpPost httpPost =newHttpPost(urlAddress);
List params =newArrayList();
NameValuePair pair1 =newBasicNameValuePair("username", username);
NameValuePair pair2 =newBasicNameValuePair("password", password);
params.add(pair1);
params.add(pair2);

HttpEntity he;
try{
he =newUrlEncodedFormEntity(params, "gbk");
httpPost.setEntity(he);

}catch(UnsupportedEncodingException e1) {
//TODO Auto-generated catch block
e1.printStackTrace();
}

HttpClient hc =newDefaultHttpClient();
try{
HttpResponse ht = hc.execute(httpPost);
//连接成功
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity het = ht.getEntity();
InputStream is = het.getContent();
BufferedReader br =newBufferedReader(newInputStreamReader(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);
System.out.println("=========&&"+response);
returnresponse;
}else{
return"error";
}
}catch(ClientProtocolException e) {
//TODO Auto-generated catch block
e.printStackTrace();
return"exception";
}catch(IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
return"exception";
}
}

servlet端json转化:

resp.setContentType("text/json");
resp.setCharacterEncoding("UTF-8");
toDo =newToDo();
List<UserBean> list =newArrayList<UserBean>();
list = toDo.queryUsers(mySession);
String body;

//设定JSON
JSONArray array =newJSONArray();
for(UserBean bean : list)
{
JSONObject obj =newJSONObject();
try
{
obj.put("username", bean.getUserName());
obj.put("password", bean.getPassWord());
}catch(Exception e){}
array.add(obj);
}
pw.write(array.toString());
System.out.println(array.toString());

android端接收:

String urlAddress = "http://192.168.1.102:8080/qualityserver/result.do";
String body =
getContent(urlAddress);
JSONArray array =newJSONArray(body);
for(inti=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 =newHashMap<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) {
//TODO Auto-generated catch block
e.printStackTrace();
}

if(sb!=null)
{
showResult.setText("用户名和密码信息:");
showResult.setTextSize(20);
}else
extracted();

//设置adapter
SimpleAdapter simple =newSimpleAdapter(this,listItem,
android.R.layout.simple_list_item_2,
newString[]{"username","password"},
newint[]{android.R.id.text1,android.R.id.text2});
listResult.setAdapter(simple);

listResult.setOnItemClickListener(newOnItemClickListener() {
@Override
publicvoidonItemClick(AdapterView<?> parent, View view,
intposition,longid) {
intpositionId = (int) (id+1);
Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show();

}
});
}
privatevoidextracted() {
showResult.setText("没有有效的数据!");
}
//和服务器连接
privateString getContent(String url)throwsException{
StringBuilder sb =newStringBuilder();
HttpClient client =newDefaultHttpClient();
HttpParams httpParams =client.getParams();

HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpResponse response = client.execute(newHttpGet(url));
HttpEntity entity =response.getEntity();

if(entity !=null){
BufferedReader reader =newBufferedReader(newInputStreamReader
(entity.getContent(),"UTF-8"),8192);
String line =null;
while((line= reader.readLine())!=null){
sb.append(line +"\n");
}
reader.close();
}
returnsb.toString();
}
AiPPT
2024-12-03 广告
作为北京饼干科技有限公司的一员,对于市场上各类工具都有所了解。就AiPPT而言,它确实为用户提供了便捷高效的PPT制作体验。通过智能化的辅助功能,用户能够快速生成专业且富有创意的演示文稿,极大地节省了时间和精力。无论是对于个人用户还是企业团... 点击进入详情页
本回答由AiPPT提供
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式