`
hunankeda110
  • 浏览: 747050 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

android发送http请求—-URLConnection、HttpURLConnection的使用

阅读更多
1. 使用 标准Java接口: 设计的类: java.net.*
基本步骤:
1) 创建 URL 以及 URLConnection / HttpURLConnection 对象
2) 设置连接参数
3) 连接到服务器
4) 向服务器写数据
5)从服务器读取数据

例:


try {// 创建一个 URL 对象URL url = new URL(your_url);// 创建一个 URL 连接,如果有代理的话可以指定一个代理。URLConnection connection = url.openConnection(Proxy_yours);// 对于 HTTP 连接可以直接转换成 HttpURLConnection,这样就可以使用一些 HTTP 连接特定的方法,如 setRequestMethod() 等://HttpURLConnection connection =//      (HttpURLConnection)url.openConnection(Proxy_yours);// 在开始和服务器连接之前,可能需要设置一些网络参数connection.setConnectTimeout(10000);connection.addRequestProperty(“User-Agent”,“J2me/MIDP2.0″);// 连接到服务器connection.connect();// 与服务器交互:OutputStream outStream = connection.getOutputStream();ObjectOutputStream objOutput = new ObjectOutputStream(outStream);objOutput.writeObject(new String(“this is a string…”));objOutput.flush();InputStream in = connection.getInputStream();// 处理数据…} catch (Exception e) {// 网络读写操作往往会产生一些异常,所以在具体编写网络应用时// 最好捕捉每一个具体以采取相应措施}

2. 使用 apache 接口:

Apache HttpClient 是一个开源项目,弥补了 java.net.* 灵活性不足的缺点, 支持客户端的HTTP编程.
使用的类包括:  org.apache.http.*

步骤:
1) 创建 HttpClient 以及 GetMethod / PostMethod, HttpRequest 等对象;
2) 设置连接参数;
3) 执行 HTTP 操作;
4) 处理服务器返回结果.

例:


try {// 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的)HttpParams params = new BasicHttpParams();// 设置连接超时和 Socket 超时,以及 Socket 缓存大小:HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);HttpConnectionParams.setSoTimeout(params, 20 * 1000);HttpConnectionParams.setSocketBufferSize(params, 8192);// 设置重定向,缺省为 true:HttpClientParams.setRedirecting(params, true);// 设置 user agent:HttpProtocolParams.setUserAgent(params, userAgent);// 创建一个 HttpClient 实例:// 注意: HttpClient httpClient = new HttpClient(); 是Commons HttpClient中的用法,//      在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient.DefaultHttpClient httpClient = new DefaultHttpClient(params);// 创建 HttpGet 方法,该方法会自动处理 URL 地址的重定向:HttpGet httpGet = new HttpGet (“http://www.test_test.com/”);//执行此方法:HttpResponse response = client.execute(httpGet);if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {// 错误处理,例如可以在该请求正常结束前将其中断:httpGet.abort();}// 读取更多信息Header[] headers = response.getHeaders();HttpEntity entity = response.getEntity();Header header = response.getFirstHeader(“Content-Type”);} catch (Exception ee) {// …} finally {// 释放连接:client.getConnectionManager().shutdown();}以下例子以 HttpGet 方式通过代理访问 HTTPS 网站:try {HttpClient httpClient = new HttpClient();// 设置认证的数据:  httpClient好像没有方法getCredentialsProvider()??httpClient.getCredentialsProvider().setCredentials(new AuthScope(“your_auth_host”, 80, “your_realm”),new UsernamePasswordCredentials(“username”, “password”));// 设置服务器地址,端口,访问协议:HttpHost targetHost = new HttpHost(“www.verisign.com”, 443, “https”);// 设置代理:HttpHost proxy = new HttpHost(“192.168.1.1″, 80);httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);// 创建一个 HttpGet 实例:HttpGet httpGet = new HttpGet(“/a/b/c”);// 连接服务器并获取应答数据:HttpResponse response = httpClient.execute(targetHost, httpGet);// 读取应答数据:int statusCode = response.getStatusLine().getStatusCode();Header[] headers = response.getHeaders();HttpEntity entity = response.getEntity();//    …} catch (Exception ee) {//    …}

3. 使用 android 接口:

类android.net.http.* 实际上是通过对 Apache 的 HttpClient 的封装来实现的一个 HTTP 编程接口,同时还提供了 HTTP 请求队列管理、以及 HTTP 连接池管理,以提高并发请求情况下(如转载网页时)的处理效率,除此之外还有网络状态监视等接口。

例:(class AndroidHttpClient : Since Android API level

按 Ctrl+C 复制代码
try {
AndroidHttpClient client =
AndroidHttpClient.newInstance(“user_agent__my_mobile_browser”);

// 创建 HttpGet 方法,该方法会自动处理 URL 地址的重定向:
HttpGet httpGet = new HttpGet (“http://www.test_test.com/”);
HttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// 错误处理…
}
//…

// 关闭连接:
client.close();
} catch (Exception ee) {
//…
}
A Comparison of java.net.URLConnection and HTTPClient
Since java.net.URLConnection and HTTPClient have overlappingfunctionalities, the question arises of why would you use HTTPClient.Here are a few of the capabilites and tradeoffs.




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

    String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do";      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;          }      } 

HTTPClient

String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do";  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");  //hp.  //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);              System.out.println("========="+response);  return response;          }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";      }      }  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) {  // TODO Auto-generated catch block          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);              System.out.println("=========&&"+response);  return response;          }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 = new ToDo();          List<UserBean> list = new ArrayList<UserBean>();          list = toDo.queryUsers(mySession);          String body;  //设定JSON          JSONArray array = new JSONArray();  for(UserBean bean : list)          {              JSONObject obj = new JSONObject();  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 = 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) {  // TODO Auto-generated catch block              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();      } 

URLConnection
HTTPClient

Proxies and SOCKS
Full support in Netscape browser, appletviewer, and applications (SOCKS: Version 4 only); no additional limitations from security policies.
Full support (SOCKS: Version 4 and 5); limited in applets however by security policies; in Netscape can't pick up the settings from the browser.

Authorization
Full support for Basic Authorization in Netscape (can use info given by the user for normal accesses outside of the applet); no support in appletviewer or applications.
Full support everywhere; however cannot access previously given info from Netscape, thereby possibly requesting the user to enter info (s)he has already given for a previous access. Also, you can add/implement additional authentication mechanisms yourself.

Methods
Only has GET and POST.
Has HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, plus any arbitrary method.

Headers
Currently you can only set any request headers if you are doing a POST under Netscape; for GETs and the JDK you can't set any headers.
Under Netscape 3.0 you can read headers only if the resource was returned with a Content-length header; if no Content-length header was returned, or under previous versions of Netscape, or using the JDK no headers can be read.
Allows any arbitrary headers to be sent and received.

Automatic Redirection Handling
Yes.
Yes (as allowed by the HTTP/1.1 spec).

Persistent Connections
No support currently in JDK; under Netscape uses HTTP/1.0 Keep-Alive's.
Supports HTTP/1.0 Keep-Alive's and HTTP/1.1 persistence.

Pipelining of Requests
No.
Yes.

Can handle protocols other than HTTP
Theoretically; however only http is currently implemented.
No.

Can do HTTP over SSL (https)
Under Netscape, yes. Using Appletviewer or in an application, no.
No (not yet).

Source code available
No.
Yes.

分享到:
评论

相关推荐

    okhttp-2.0.0.jar+okhttp-apache-2.0.0.jar+okhttp-urlconnection-2.0.0.jar

    OKHttp是Java编程语言中的一款高效且功能强大的网络请求库,尤其在移动开发领域,如Android应用程序中,它被广泛使用。标题中的"okhttp-2.0.0.jar+okhttp-apache-2.0.0.jar+okhttp-urlconnection-2.0.0.jar"分别指的...

    HttpURLConnection OKHttp实现请求

    在Android开发中,网络请求是不可或缺的一部分,而`HttpURLConnection`和`OKHttp`是两种常用的网络请求库。本文将详细介绍这两种方式的实现原理及如何在实际项目中使用。 首先,`HttpURLConnection`是Java标准库...

    Android课件(URL+HttpURLConnection).zip

    - 尽管HttpURLConnection是原生支持的,但现代的Android开发更多倾向于使用Retrofit、OkHttp等第三方库,它们提供了更简洁、强大的网络请求功能。 以上就是关于Android中URL和HttpURLConnection的相关知识点。通过...

    Android HttpURLConnection.getResponseCode()错误解决方法

    导语:个人对网络连接接触的不多,在使用时自己发现一些问题,记录一下。 正文:我在使用HttpURLConnection.getResponseCode()的时候直接报错是... 您可能感兴趣的文章:Android使用URLConnection提交请求的实现Androi

    Android使用HttpURLConnection访问网络

    本篇文章将深入探讨如何在Android应用中利用HttpURLConnection访问网络,包括设置请求方法、添加请求头、处理响应以及解决常见问题。 1. HttpURLConnection简介: HttpURLConnection是Java内置的类,它是...

    Android基于HttpUrlConnection类的文件下载实例代码

    Android操作系统中,文件下载是一种常见的功能,为了实现文件下载,Android提供了多种方式,包括使用HttpUrlConnection类和OkHttp库等。HttpUrlConnection类是Android系统中的一种基本的网络请求方式,通过该类可以...

    Android HttpURLConnection 读取网络图片.rar

     这次的HttpURLConnection仅针对Http连接,效率胜于URLConnection。new URL对象将网址传入  HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();// 取得连接  conn.connect();  ...

    java android httpURLConnection的封装

    此类处理了底层的细节,如使用URL和URLConnection打开一个网络连接,通过输出流发送请求数据,以及通过输入流接收响应数据。这里还涉及到字符编码的转换,常用字符编码有ISO_8859_1、UTF_8、GBK和GB2312等。在处理...

    UrlConnection连接和Socket连接的区别

    `HttpURLConnectionImpl.java`就是`HttpURLConnection`的具体实现类,它包含了HTTP请求的完整生命周期,包括打开连接、设置请求方法、发送数据、接收响应等步骤。在使用`UrlConnection`时,我们通常会通过`open...

    Android-一个可以创建触发任意HTTP请求的主屏幕快捷方式的Android应用

    在Android中,发送HTTP请求通常使用`HttpURLConnection`类(对于API级别23以上)或`java.net.URL`和`java.net.URLConnection`类,或者使用第三方库如Volley、OkHttp等。考虑到此应用的简单性,它可能使用了`...

    android-http-client.7z

    本资源"android-http-client.7z"很可能包含了一个或多个用于Android平台的HTTP客户端实现,可能是开源库或者自定义实现。以下是对Android HTTP客户端相关知识点的详细解释: 1. **HttpURLConnection**:这是Android...

    Android Studio调用RestfulWCF接口

    在 Android Studio 中调用 Restful WCF 接口需要使用 Java 的标准类 HttpURLConnection,该类继承自 URLConnection,提供了访问 HTTP 协议的基本功能,能够向指定网站发送 GET 请求和 POST 请求。但是,在 Android ...

    Android开发使用URLConnection进行网络编程详解

    Android 开发使用 URLConnection 进行网络编程详解 Android 开发使用 URLConnection ...使用 URLConnection 进行网络编程可以实现网络数据的交换,但需要注意设置请求头字段的值、发送请求参数、读取响应数据等细节。

    Android HTTP 客户端编程.pdf

    本节主要讨论如何在Android平台上实现HTTP通信,特别是使用HttpUrlConnection接口来发送GET和POST请求。 Android的HTTP客户端编程主要涉及到以下几个核心概念: 1. **HTTP协议**:超文本传输协议(HTTP)是一种...

    android http开发视频

    - 在较旧的Android版本中,开发者通常使用`HttpURLConnection`类来执行HTTP请求,但其API较为复杂且不友好。 - `HttpClient`是另一种常见的选择,但在Android API 23之后被弃用。 - 现在推荐使用第三方库,如`...

    Android4.0网络编程详解.pdf

    - Android 4.0允许开发者通过URL类打开网络连接,通过URLConnection类可以发送请求并读取响应。 3. 使用HttpURLConnection: - HttpURLConnection类继承自URLConnection,专门用于处理HTTP协议的请求和响应。 - ...

    Android 中HttpURLConnection与HttpClient使用的简单实例

    本文将详细介绍如何在Android中使用这两种方法进行网络请求,并提供简单的实例。 首先,我们来看使用HttpURLConnection的方式。HttpURLConnection是Java标准库提供的类,它直接继承自URLConnection,支持HTTP和...

    androidhttp

    HttpURLConnection 是 Android SDK 内置的 HTTP 客户端,它基于 Java 的 URLConnection 类,适用于简单的 HTTP 请求。使用 HttpURLConnection 可以实现 GET 和 POST 等多种请求方法。以下是如何使用 ...

    Android基础 网络通信

    在Android中,我们通常使用`HttpURLConnection`或第三方库如OkHttp进行HTTP请求。 - **HTTPS(安全套接层超文本传输协议)** 是HTTP的安全版本,它通过SSL/TLS协议提供加密处理、服务器身份验证和消息完整性检查,...

    xamarin学习笔记A15(安卓OkHttp3和HttpURLConnection)上

    3. 发送请求时,需要打开一个URLConnection,设置请求方法,然后写入请求体(如果需要POST请求)。读取响应时,需要处理输入流。这个过程相比OkHttp3来说更为繁琐,也更容易出错。 三、选择与比较 1. 在选择OkHttp...

Global site tag (gtag.js) - Google Analytics