Android HttpURLConnection(Get,Post方式)进行网络通信 获取数据和网络图片

前言
         欢迎大家我分享和推荐好用的代码段~~
声明
         欢迎转载,但请保留文章原始出处:
         CSDN
http://www.csdn.net
         雨季o莫忧离:http://blog.csdn.net/luckkof

正文

 

Http通信中使用的最多的是Get和Post。Get请求可以获取静态页面,也可以把参数放在url字符串后面传递给服务器。Post与Get的不同之处在于Post的参数不是放在url字符串里面,而是放在http请求数据中。HttpURLConnection是Java的标准类,继承自URLConnection类,URLConnection与 HttpURLConnection都是抽象类,去、、无法直接实例化对象。其对象主要通过URL的openConnection方法获得。下面就两种方式分别提供示例:

其中有两个资源文件,两个jsp的内容分别如下:
http.jsp
[html] view plaincopy
  1. <html>  
  2.   <head>   
  3.     <title>My JSP 'index.jsp' starting page</title>  
  4.   </head>  
  5.   <body>  
  6.     <%  
  7.         out.println("<h1>HTTP TEST<br/>http test</h1>");  
  8.      %>  
  9.   </body>  
  10. </html>  
httpGet.jsp
[html] view plaincopy
  1. <html>  
  2.   <head>  
  3.     <title>My JSP 'index.jsp' starting page</title>  
  4.   </head>   
  5.   <body>  
  6.     <%  
  7.         String type = request.getParameter("par");  
  8.         String result = new String(type.getBytes("iso-8859-1"),"gb2312");  
  9.         out.println("<h1>parameters:"+result+"</h1>");  
  10.      %>  
  11.   </body>  
  12. </html>  

1、  HttpURLConnection 类通过Get方式获取网络资源:

[java] view plaincopy
  1. public class GetActivity extends Activity {  
  2.     private String TAG = "GetActivity";  
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.http);  
  7.         TextView textView = (TextView)findViewById(R.id.text);  
  8.           
  9.         String urlString = "http://127.0.0.1:8080/test/httpGet.jsp?par=test";//http地址  
  10.         String resultData = "";//获得的数据  
  11.         URL url = null;  
  12.         try {  
  13.             url = new URL(urlString);//构造一个url对象  
  14.         } catch (MalformedURLException e) {  
  15.             Log.e(TAG, "MalformedURLException");  
  16.             e.printStackTrace();  
  17.         }  
  18.         if(url!=null){  
  19.             try {  
  20.                 HttpURLConnection urlConnection;//使用HttpURLConnection打开连接  
  21.                 urlConnection = (HttpURLConnection)url.openConnection();  
  22.                 InputStream stream = urlConnection.getInputStream();//得到读取的内容  
  23.                 InputStreamReader in = new InputStreamReader(stream);  
  24.                 BufferedReader buffere = new BufferedReader(in);    //为输出创建BufferedReader  
  25.                 String line = null;  
  26.                 while((line = buffere.readLine()) != null){//使用while循环来取得获取的数据  
  27.                     resultData += line + "\n";//我们要在每一行的后面加上一个反斜杠来换行  
  28.                 }  
  29.                 if(resultData.equals("")){  
  30.                     textView.setText("没取到数据");  
  31.                 }else{  
  32.                     textView.setText(resultData);  
  33.                 }  
  34.                 in.close();//关闭InputStreamReader  
  35.                 urlConnection.disconnect();//关闭http连接  
  36.             } catch (IOException e) {  
  37.                 Log.e(TAG, "IOException");  
  38.                 e.printStackTrace();  
  39.             }  
  40.         }else{  
  41.             Log.e(TAG, "url null");  
  42.         }  
  43.     }  
  44. }  

2、 HttpURLConnection 类通过Post方式获取网络资源:

[java] view plaincopy
  1. public class PostActivity extends Activity {  
  2.   
  3.     private String TAG="PostActivity";  
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         // TODO Auto-generated method stub  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.http);  
  9.         TextView textView = (TextView)findViewById(R.id.text);  
  10.           
  11.         String httpUrl = "http://127.0.0.1:8080/test/httpGet.jsp";  
  12.         String resultData = "";  
  13.         URL url = null;  
  14.         try {  
  15.             url = new URL(httpUrl);  
  16.         } catch (MalformedURLException e) {  
  17.             // TODO Auto-generated catch block  
  18.             Log.e(TAG, "MalformedURLException");  
  19.             e.printStackTrace();  
  20.         }  
  21.         if(url!=null){  
  22.             //使用HttpURLConnection打开连接  
  23.             HttpURLConnection urlConnection;  
  24.             try {  
  25.                 urlConnection = (HttpURLConnection)url.openConnection();  
  26.                 //因为这个是post请求,需要设置为true  
  27.                 urlConnection.setDoOutput(true);  
  28.                 urlConnection.setDoInput(true);  
  29.                 //设置以Post方法  
  30.                 urlConnection.setUseCaches(false);  
  31.                 urlConnection.setInstanceFollowRedirects(true);  
  32.                 //配置本次连接的Content-type  
  33.                 urlConnection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  34.                 //从url.openConnection()至此的配置必须在connect之前完成,要注意的是:  
  35.                 //connection.getOutputStream会隐含的进行connect  
  36.                 urlConnection.connect();  
  37.                 //DataOutputStream流  
  38.                 DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());  
  39.                 //要上传的参数  
  40.                 String content = "par=" + URLEncoder.encode("ABCD""gb2312");  
  41.                 //将要上传的内容写入流中  
  42.                 outputStream.writeBytes(content);  
  43.                 //刷新,关闭  
  44.                 outputStream.flush();  
  45.                 outputStream.close();  
  46.                 //取得数据  
  47.                 BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));  
  48.                 String line = null;  
  49.                 //使用循环体来获得数据  
  50.                 while((line = reader.readLine())!=null){  
  51.                     resultData += line + "\n";  
  52.                 }  
  53.                 if(!resultData.equals("")){  
  54.                     textView.setText(resultData);  
  55.                 }else{  
  56.                     textView.setText("读取的内容为null");  
  57.                 }  
  58.                 reader.close();  
  59.                 //关闭http连接  
  60.                 urlConnection.disconnect();  
  61.             } catch (IOException e) {  
  62.                 // TODO Auto-generated catch block  
  63.                 Log.e(TAG, "IOException");  
  64.                 e.printStackTrace();  
  65.             }  
  66.         }else{  
  67.             Log.e(TAG, "url null");  
  68.         }  
  69.     }  
  70. }  

3、获取网络图片的代码:

[java] view plaincopy
  1. public class ImageActivity extends Activity {  
  2.   
  3.     private String TAG = "ImageActivity";  
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         // TODO Auto-generated method stub  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.image);  
  9.         ImageView imageView = (ImageView)findViewById(R.id.image);  
  10.         Button button = (Button)findViewById(R.id.button);  
  11.         button.setOnClickListener(new OnClickListener() {  
  12.             @Override  
  13.             public void onClick(View v) {  
  14.                 // TODO Auto-generated method stub  
  15.                 Intent intent = new Intent(ImageActivity.this, MainActivity.class);  
  16.                 startActivity(intent);  
  17.             }  
  18.         });  
  19.         String urlString = "http://www.eoeandroid.com/data/attachment/forum/201107/18/142935bbi8d3zpf3d0dd7z.jpg";  
  20.         URL imageUrl = null;  
  21.         Bitmap bitmap = null;  
  22.         try{  
  23.             imageUrl = new URL(urlString);  
  24.         }catch (MalformedURLException e) {  
  25.             // TODO: handle exception  
  26.             Log.e(TAG, "MalformedURLException");  
  27.             e.printStackTrace();  
  28.         }  
  29.         try{  
  30.             HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();  
  31.             connection.setDoInput(true);  
  32.             connection.connect();  
  33.             //将得到的数据转换为InputStream  
  34.             InputStream is = connection.getInputStream();  
  35.             //将InputStream转换为Bitmap  
  36.             bitmap = BitmapFactory.decodeStream(is);  
  37.             is.close();  
  38.         }catch (IOException e) {  
  39.             // TODO: handle exception  
  40.             Log.e(TAG, "IOException");  
  41.         }  
  42.         if(bitmap == null){  
  43.             Log.i(TAG, "没取到数据");  
  44.         }else{  
  45.             imageView.setImageBitmap(bitmap);  
  46.         }  
  47.     }  
  48.       
  49. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值