转自:http://lpqsun-126-com.iteye.com/blog/1084311

Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。以下是本人在学习中的总结与归纳。
1. HttpURLConnection接口
首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器。而POST方法的参数是放在Http请求中。因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式。

HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得。创建方法如下代码所示:

Java代码
  1. URLurl=newURL("http://www.51cto.com/index.jsp?par=123456");
  2. HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();

通过以下方法可以对请求的属性进行一些设置,如下所示

Java代码
  1. //设置输入和输出流
  2. urlConn.setDoOutput(true);
  3. urlConn.setDoInput(true);
  4. //设置请求方式为POST
  5. urlConn.setRequestMethod("POST");
  6. //POST请求不能使用缓存
  7. urlConn.setUseCaches(false);
  8. //关闭连接
  9. urlConn.disConnection();

Manifest文件中权限的设定:

Xml代码
  1. <uses-permissionandroid:name="android.permission.INTERNET"/>

HttpURLConnection默认使用GET方式,例如下面代码所示:

Java代码
  1. //以Get方式上传参数
  2. publicclassActivity03extendsActivity
  3. {
  4. privatefinalStringDEBUG_TAG="Activity03";
  5. /**Calledwhentheactivityisfirstcreated.*/
  6. @Override
  7. publicvoidonCreate(BundlesavedInstanceState)
  8. {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.http);
  11. TextViewmTextView=(TextView)this.findViewById(R.id.TextView_HTTP);
  12. //http地址"?par=abcdefg"是我们上传的参数
  13. StringhttpUrl="http://192.168.1.110:8080/httpget.jsp?par=abcdefg";
  14. //获得的数据
  15. StringresultData="";
  16. URLurl=null;
  17. try
  18. {
  19. //构造一个URL对象
  20. url=newURL(httpUrl);
  21. }
  22. catch(MalformedURLExceptione)
  23. {
  24. Log.e(DEBUG_TAG,"MalformedURLException");
  25. }
  26. if(url!=null)
  27. {
  28. try
  29. {
  30. //使用HttpURLConnection打开连接
  31. HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();
  32. //得到读取的内容(流)
  33. InputStreamReaderin=newInputStreamReader(urlConn.getInputStream());
  34. //为输出创建BufferedReader
  35. BufferedReaderbuffer=newBufferedReader(in);
  36. StringinputLine=null;
  37. //使用循环来读取获得的数据
  38. while(((inputLine=buffer.readLine())!=null))
  39. {
  40. //我们在每一行后面加上一个"\n"来换行
  41. resultData+=inputLine+"\n";
  42. }
  43. //关闭InputStreamReader
  44. in.close();
  45. //关闭http连接
  46. urlConn.disconnect();
  47. //设置显示取得的内容
  48. if(resultData!=null)
  49. {
  50. mTextView.setText(resultData);
  51. }
  52. else
  53. {
  54. mTextView.setText("读取的内容为NULL");
  55. }
  56. }
  57. catch(IOExceptione)
  58. {
  59. Log.e(DEBUG_TAG,"IOException");
  60. }
  61. }
  62. else
  63. {
  64. Log.e(DEBUG_TAG,"UrlNULL");
  65. }
  66. }

如果需要使用POST方式,则需要setRequestMethod设置。代码如下:

Java代码
  1. //以post方式上传参数
  2. publicclassActivity04extendsActivity
  3. {
  4. privatefinalStringDEBUG_TAG="Activity04";
  5. /**Calledwhentheactivityisfirstcreated.*/
  6. @Override
  7. publicvoidonCreate(BundlesavedInstanceState)
  8. {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.http);
  11. TextViewmTextView=(TextView)this.findViewById(R.id.TextView_HTTP);
  12. //http地址"?par=abcdefg"是我们上传的参数
  13. StringhttpUrl="http://192.168.1.110:8080/httpget.jsp";
  14. //获得的数据
  15. StringresultData="";
  16. URLurl=null;
  17. try
  18. {
  19. //构造一个URL对象
  20. url=newURL(httpUrl);
  21. }
  22. catch(MalformedURLExceptione)
  23. {
  24. Log.e(DEBUG_TAG,"MalformedURLException");
  25. }
  26. if(url!=null)
  27. {
  28. try
  29. {
  30. //使用HttpURLConnection打开连接
  31. HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();
  32. //因为这个是post请求,设立需要设置为true
  33. urlConn.setDoOutput(true);
  34. urlConn.setDoInput(true);
  35. //设置以POST方式
  36. urlConn.setRequestMethod("POST");
  37. //Post请求不能使用缓存
  38. urlConn.setUseCaches(false);
  39. urlConn.setInstanceFollowRedirects(true);
  40. //配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
  41. urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  42. //连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
  43. //要注意的是connection.getOutputStream会隐含的进行connect。
  44. urlConn.connect();
  45. //DataOutputStream流
  46. DataOutputStreamout=newDataOutputStream(urlConn.getOutputStream());
  47. //要上传的参数
  48. Stringcontent="par="+URLEncoder.encode("ABCDEFG","gb2312");
  49. //将要上传的内容写入流中
  50. out.writeBytes(content);
  51. //刷新、关闭
  52. out.flush();
  53. out.close();
  54. //获取数据
  55. BufferedReaderreader=newBufferedReader(newInputStreamReader(urlConn.getInputStream()));
  56. StringinputLine=null;
  57. //使用循环来读取获得的数据
  58. while(((inputLine=reader.readLine())!=null))
  59. {
  60. //我们在每一行后面加上一个"\n"来换行
  61. resultData+=inputLine+"\n";
  62. }
  63. reader.close();
  64. //关闭http连接
  65. urlConn.disconnect();
  66. //设置显示取得的内容
  67. if(resultData!=null)
  68. {
  69. mTextView.setText(resultData);
  70. }
  71. else
  72. {
  73. mTextView.setText("读取的内容为NULL");
  74. }
  75. }
  76. catch(IOExceptione)
  77. {
  78. Log.e(DEBUG_TAG,"IOException");
  79. }
  80. }
  81. else
  82. {
  83. Log.e(DEBUG_TAG,"UrlNULL");
  84. }
  85. }
  86. }

2. HttpClient接口
使用Apache提供的HttpClient接口同样可以进行HTTP操作。
对于GET和POST请求方法的操作有所不同。GET方法的操作代码示例如下:

Java代码
  1. publicclassActivity02extendsActivity
  2. {
  3. /**Calledwhentheactivityisfirstcreated.*/
  4. @Override
  5. publicvoidonCreate(BundlesavedInstanceState)
  6. {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.http);
  9. TextViewmTextView=(TextView)this.findViewById(R.id.TextView_HTTP);
  10. //http地址
  11. StringhttpUrl="http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
  12. //HttpGet连接对象
  13. HttpGethttpRequest=newHttpGet(httpUrl);
  14. try
  15. {
  16. //取得HttpClient对象
  17. HttpClienthttpclient=newDefaultHttpClient();
  18. //请求HttpClient,取得HttpResponse
  19. HttpResponsehttpResponse=httpclient.execute(httpRequest);
  20. //请求成功
  21. if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
  22. {
  23. //取得返回的字符串
  24. StringstrResult=EntityUtils.toString(httpResponse.getEntity());
  25. mTextView.setText(strResult);
  26. }
  27. else
  28. {
  29. mTextView.setText("请求错误!");
  30. }
  31. }
  32. catch(ClientProtocolExceptione)
  33. {
  34. mTextView.setText(e.getMessage().toString());
  35. }
  36. catch(IOExceptione)
  37. {
  38. mTextView.setText(e.getMessage().toString());
  39. }
  40. catch(Exceptione)
  41. {
  42. mTextView.setText(e.getMessage().toString());
  43. }
  44. }
  45. }

使用POST方法进行参数传递时,需要使用NameValuePair来保存要传递的参数,另外,还需要设置所使用的字符集。代码如下所示:

Java代码
  1. publicclassActivity03extendsActivity
  2. {
  3. /**Calledwhentheactivityisfirstcreated.*/
  4. @Override
  5. publicvoidonCreate(BundlesavedInstanceState)
  6. {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.http);
  9. TextViewmTextView=(TextView)this.findViewById(R.id.TextView_HTTP);
  10. //http地址
  11. StringhttpUrl="http://192.168.1.110:8080/httpget.jsp";
  12. //HttpPost连接对象
  13. HttpPosthttpRequest=newHttpPost(httpUrl);
  14. //使用NameValuePair来保存要传递的Post参数
  15. List<NameValuePair>params=newArrayList<NameValuePair>();
  16. //添加要传递的参数
  17. params.add(newBasicNameValuePair("par","HttpClient_android_Post"));
  18. try
  19. {
  20. //设置字符集
  21. HttpEntityhttpentity=newUrlEncodedFormEntity(params,"gb2312");
  22. //请求httpRequest
  23. httpRequest.setEntity(httpentity);
  24. //取得默认的HttpClient
  25. HttpClienthttpclient=newDefaultHttpClient();
  26. //取得HttpResponse
  27. HttpResponsehttpResponse=httpclient.execute(httpRequest);
  28. //HttpStatus.SC_OK表示连接成功
  29. if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
  30. {
  31. //取得返回的字符串
  32. StringstrResult=EntityUtils.toString(httpResponse.getEntity());
  33. mTextView.setText(strResult);
  34. }
  35. else
  36. {
  37. mTextView.setText("请求错误!");
  38. }
  39. }
  40. catch(ClientProtocolExceptione)
  41. {
  42. mTextView.setText(e.getMessage().toString());
  43. }
  44. catch(IOExceptione)
  45. {
  46. mTextView.setText(e.getMessage().toString());
  47. }
  48. catch(Exceptione)
  49. {
  50. mTextView.setText(e.getMessage().toString());
  51. }
  52. }
  53. }

HttpClient实际上是对Java提供方法的一些封装,在HttpURLConnection中的输入输出流操作,在这个接口中被统一封装成了HttpPost(HttpGet)和HttpResponse,这样,就减少了操作的繁琐性。

另外,在使用POST方式进行传输时,需要进行字符编码。编辑器加载中...

更多相关文章

  1. Linux 下使用 NDK 编译 protobuf 2.6.1
  2. android的一些开发的资源
  3. Android控制手电筒代码,简单易用,不需要任何权限
  4. 2018年Android最新面试题
  5. Android中Http请求
  6. Android(安卓)studio 下的svn配置使用
  7. 箭头函数的基础使用
  8. NPM 和webpack 的基础使用
  9. Python list sort方法的具体使用

随机推荐

  1. 微信稳居Android(安卓)App排行榜4月份国
  2. java个推实战,Android和Ios
  3. Android(安卓)为什么主线程的looper 一直
  4. MacAndroid源码下载 Android10详解
  5. 一起Talk Android吧(第二百六十五回:Androi
  6. Android中Activity, View,Window,DecorVi
  7. Android(安卓)Socket与HTTPS校验
  8. 超新鲜的字节客户端Android面经,附面试题
  9. 2015年11月广师android群内容分享
  10. Android手机分辨率问题