android发送http请求—-URLConnection、HttpURLConnection的使用
1.使用标准Java接口:设计的类:java.net.*
基本步骤:
1)创建URL以及URLConnection/HttpURLConnection对象
2)设置连接参数
3)连接到服务器
4)向服务器写数据
5)从服务器读取数据
例:
try{//创建一个URL对象URLurl=newURL(your_url);//创建一个URL连接,如果有代理的话可以指定一个代理。URLConnectionconnection=url.openConnection(Proxy_yours);//对于HTTP连接可以直接转换成HttpURLConnection,这样就可以使用一些HTTP连接特定的方法,如setRequestMethod()等://HttpURLConnectionconnection=//(HttpURLConnection)url.openConnection(Proxy_yours);//在开始和服务器连接之前,可能需要设置一些网络参数connection.setConnectTimeout(10000);connection.addRequestProperty(“User-Agent”,“J2me/MIDP2.0″);//连接到服务器connection.connect();//与服务器交互:OutputStreamoutStream=connection.getOutputStream();ObjectOutputStreamobjOutput=newObjectOutputStream(outStream);objOutput.writeObject(newString(“thisisastring…”));objOutput.flush();InputStreamin=connection.getInputStream();//处理数据…}catch(Exceptione){//网络读写操作往往会产生一些异常,所以在具体编写网络应用时//最好捕捉每一个具体以采取相应措施}
2.使用apache接口:
ApacheHttpClient是一个开源项目,弥补了java.net.*灵活性不足的缺点,支持客户端的HTTP编程.
使用的类包括:org.apache.http.*
步骤:
1)创建HttpClient以及GetMethod/PostMethod,HttpRequest等对象;
2)设置连接参数;
3)执行HTTP操作;
4)处理服务器返回结果.
例:
try{//创建HttpParams以用来设置HTTP参数(这一部分不是必需的)HttpParamsparams=newBasicHttpParams();//设置连接超时和Socket超时,以及Socket缓存大小:HttpConnectionParams.setConnectionTimeout(params,20*1000);HttpConnectionParams.setSoTimeout(params,20*1000);HttpConnectionParams.setSocketBufferSize(params,8192);//设置重定向,缺省为true:HttpClientParams.setRedirecting(params,true);//设置useragent:HttpProtocolParams.setUserAgent(params,userAgent);//创建一个HttpClient实例://注意:HttpClienthttpClient=newHttpClient();是CommonsHttpClient中的用法,//在Android1.5中我们需要使用Apache的缺省实现DefaultHttpClient.DefaultHttpClienthttpClient=newDefaultHttpClient(params);//创建HttpGet方法,该方法会自动处理URL地址的重定向:HttpGethttpGet=newHttpGet(“http://www.test_test.com/”);//执行此方法:HttpResponseresponse=client.execute(httpGet);if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){//错误处理,例如可以在该请求正常结束前将其中断:httpGet.abort();}//读取更多信息Header[]headers=response.getHeaders();HttpEntityentity=response.getEntity();Headerheader=response.getFirstHeader(“Content-Type”);}catch(Exceptionee){//…}finally{//释放连接:client.getConnectionManager().shutdown();}以下例子以HttpGet方式通过代理访问HTTPS网站:try{HttpClienthttpClient=newHttpClient();//设置认证的数据:httpClient好像没有方法getCredentialsProvider()??httpClient.getCredentialsProvider().setCredentials(newAuthScope(“your_auth_host”,80,“your_realm”),newUsernamePasswordCredentials(“username”,“password”));//设置服务器地址,端口,访问协议:HttpHosttargetHost=newHttpHost(“www.verisign.com”,443,“https”);//设置代理:HttpHostproxy=newHttpHost(“192.168.1.1″,80);httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);//创建一个HttpGet实例:HttpGethttpGet=newHttpGet(“/a/b/c”);//连接服务器并获取应答数据:HttpResponseresponse=httpClient.execute(targetHost,httpGet);//读取应答数据:intstatusCode=response.getStatusLine().getStatusCode();Header[]headers=response.getHeaders();HttpEntityentity=response.getEntity();//…}catch(Exceptionee){//…}
3.使用android接口:
类android.net.http.*实际上是通过对Apache的HttpClient的封装来实现的一个HTTP编程接口,同时还提供了HTTP请求队列管理、以及HTTP连接池管理,以提高并发请求情况下(如转载网页时)的处理效率,除此之外还有网络状态监视等接口。
例:(classAndroidHttpClient:SinceAndroidAPIlevel
按Ctrl+C复制代码
try{
AndroidHttpClientclient=
AndroidHttpClient.newInstance(“user_agent__my_mobile_browser”);
//创建HttpGet方法,该方法会自动处理URL地址的重定向:
HttpGethttpGet=newHttpGet(“http://www.test_test.com/”);
HttpResponseresponse=client.execute(httpGet);
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
//错误处理…
}
//…
//关闭连接:
client.close();
}catch(Exceptionee){
//…
}
AComparisonofjava.net.URLConnectionandHTTPClient
Sincejava.net.URLConnectionandHTTPClienthaveoverlappingfunctionalities,thequestionarisesofwhywouldyouuseHTTPClient.Hereareafewofthecapabilitesandtradeoffs.
HttpURLConnection与HttpClient的区别
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.案例
URLConnection
StringurlAddress="http://192.168.1.102:8080/AndroidServer/login.do";URLurl;HttpURLConnectionuRLConnection;publicUrlConnectionToServer(){}
//向服务器发送get请求publicStringdoGet(Stringusername,Stringpassword){StringgetUrl=urlAddress+"?username="+username+"&password="+password;try{url=newURL(getUrl);uRLConnection=(HttpURLConnection)url.openConnection();InputStreamis=uRLConnection.getInputStream();BufferedReaderbr=newBufferedReader(newInputStreamReader(is));Stringresponse="";StringreadLine=null;while((readLine=br.readLine())!=null){//response=br.readLine();response=response+readLine;}is.close();br.close();uRLConnection.disconnect();returnresponse;}catch(MalformedURLExceptione){e.printStackTrace();returnnull;}catch(IOExceptione){e.printStackTrace();returnnull;}}
//向服务器发送post请求publicStringdoPost(Stringusername,Stringpassword){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();DataOutputStreamout=newDataOutputStream(uRLConnection.getOutputStream());Stringcontent="username="+username+"&password="+password;out.writeBytes(content);out.flush();out.close();InputStreamis=uRLConnection.getInputStream();BufferedReaderbr=newBufferedReader(newInputStreamReader(is));Stringresponse="";StringreadLine=null;while((readLine=br.readLine())!=null){//response=br.readLine();response=response+readLine;}is.close();br.close();uRLConnection.disconnect();returnresponse;}catch(MalformedURLExceptione){e.printStackTrace();returnnull;}catch(IOExceptione){e.printStackTrace();returnnull;}}
HTTPClient
StringurlAddress="http://192.168.1.102:8080/qualityserver/login.do";publicHttpClientServer(){}publicStringdoGet(Stringusername,Stringpassword){StringgetUrl=urlAddress+"?username="+username+"&password="+password;HttpGethttpGet=newHttpGet(getUrl);HttpParamshp=httpGet.getParams();hp.getParameter("true");//hp.//httpGet.setpHttpClienthc=newDefaultHttpClient();try{HttpResponseht=hc.execute(httpGet);if(ht.getStatusLine().getStatusCode()==HttpStatus.SC_OK){HttpEntityhe=ht.getEntity();InputStreamis=he.getContent();BufferedReaderbr=newBufferedReader(newInputStreamReader(is));Stringresponse="";StringreadLine=null;while((readLine=br.readLine())!=null){//response=br.readLine();response=response+readLine;}is.close();br.close();//Stringstr=EntityUtils.toString(he);System.out.println("========="+response);returnresponse;}else{return"error";}}catch(ClientProtocolExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();return"exception";}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();return"exception";}}publicStringdoPost(Stringusername,Stringpassword){//StringgetUrl=urlAddress+"?username="+username+"&password="+password;HttpPosthttpPost=newHttpPost(urlAddress);Listparams=newArrayList();NameValuePairpair1=newBasicNameValuePair("username",username);NameValuePairpair2=newBasicNameValuePair("password",password);params.add(pair1);params.add(pair2);HttpEntityhe;try{he=newUrlEncodedFormEntity(params,"gbk");httpPost.setEntity(he);}catch(UnsupportedEncodingExceptione1){//TODOAuto-generatedcatchblocke1.printStackTrace();}HttpClienthc=newDefaultHttpClient();try{HttpResponseht=hc.execute(httpPost);//连接成功if(ht.getStatusLine().getStatusCode()==HttpStatus.SC_OK){HttpEntityhet=ht.getEntity();InputStreamis=het.getContent();BufferedReaderbr=newBufferedReader(newInputStreamReader(is));Stringresponse="";StringreadLine=null;while((readLine=br.readLine())!=null){//response=br.readLine();response=response+readLine;}is.close();br.close();//Stringstr=EntityUtils.toString(he);System.out.println("=========&&"+response);returnresponse;}else{return"error";}}catch(ClientProtocolExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();return"exception";}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();return"exception";}}
servlet端json转化:
resp.setContentType("text/json");resp.setCharacterEncoding("UTF-8");toDo=newToDo();List<UserBean>list=newArrayList<UserBean>();list=toDo.queryUsers(mySession);Stringbody;//设定JSONJSONArrayarray=newJSONArray();for(UserBeanbean:list){JSONObjectobj=newJSONObject();try{obj.put("username",bean.getUserName());obj.put("password",bean.getPassWord());}catch(Exceptione){}array.add(obj);}pw.write(array.toString());System.out.println(array.toString());
android端接收:
StringurlAddress="http://192.168.1.102:8080/qualityserver/result.do";Stringbody=getContent(urlAddress);JSONArrayarray=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(JSONExceptione){e.printStackTrace();}map.put("username",userName);map.put("password",passWord);listItem.add(map);}}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}if(sb!=null){showResult.setText("用户名和密码信息:");showResult.setTextSize(20);}elseextracted();//设置adapterSimpleAdaptersimple=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(){@OverridepublicvoidonItemClick(AdapterView<?>parent,Viewview,intposition,longid){intpositionId=(int)(id+1);Toast.makeText(MainActivity.this,"ID:"+positionId,Toast.LENGTH_LONG).show();}});}privatevoidextracted(){showResult.setText("没有有效的数据!");}//和服务器连接privateStringgetContent(Stringurl)throwsException{StringBuildersb=newStringBuilder();HttpClientclient=newDefaultHttpClient();HttpParamshttpParams=client.getParams();HttpConnectionParams.setConnectionTimeout(httpParams,3000);HttpConnectionParams.setSoTimeout(httpParams,5000);HttpResponseresponse=client.execute(newHttpGet(url));HttpEntityentity=response.getEntity();if(entity!=null){BufferedReaderreader=newBufferedReader(newInputStreamReader(entity.getContent(),"UTF-8"),8192);Stringline=null;while((line=reader.readLine())!=null){sb.append(line+"\n");}reader.close();}returnsb.toString();}
URLConnection
HTTPClient
ProxiesandSOCKS
FullsupportinNetscapebrowser,appletviewer,andapplications(SOCKS:Version4only);noadditionallimitationsfromsecuritypolicies.
Fullsupport(SOCKS:Version4and5);limitedinappletshoweverbysecuritypolicies;inNetscapecan'tpickupthesettingsfromthebrowser.
Authorization
FullsupportforBasicAuthorizationinNetscape(canuseinfogivenbytheuserfornormalaccessesoutsideoftheapplet);nosupportinappletviewerorapplications.
Fullsupporteverywhere;howevercannotaccesspreviouslygiveninfofromNetscape,therebypossiblyrequestingtheusertoenterinfo(s)hehasalreadygivenforapreviousaccess.Also,youcanadd/implementadditionalauthenticationmechanismsyourself.
Methods
OnlyhasGETandPOST.
HasHEAD,GET,POST,PUT,DELETE,TRACEandOPTIONS,plusanyarbitrarymethod.
Headers
CurrentlyyoucanonlysetanyrequestheadersifyouaredoingaPOSTunderNetscape;forGETsandtheJDKyoucan'tsetanyheaders.
UnderNetscape3.0youcanreadheadersonlyiftheresourcewasreturnedwithaContent-lengthheader;ifnoContent-lengthheaderwasreturned,orunderpreviousversionsofNetscape,orusingtheJDKnoheaderscanberead.
Allowsanyarbitraryheaderstobesentandreceived.
AutomaticRedirectionHandling
Yes.
Yes(asallowedbytheHTTP/1.1spec).
PersistentConnections
NosupportcurrentlyinJDK;underNetscapeusesHTTP/1.0Keep-Alive's.
SupportsHTTP/1.0Keep-Alive'sandHTTP/1.1persistence.
PipeliningofRequests
No.
Yes.
CanhandleprotocolsotherthanHTTP
Theoretically;howeveronlyhttpiscurrentlyimplemented.
No.
CandoHTTPoverSSL(https)
UnderNetscape,yes.UsingAppletviewerorinanapplication,no.
No(notyet).
Sourcecodeavailable
No.
Yes.