get/post请求网络服务的工具类

来源:互联网 发布:男友生日礼物 知乎 编辑:程序博客网 时间:2024/06/13 22:05
package com.bwie.utils;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import android.util.Log;public class NetWorkUtils {private static final String JSON_URL = "http://www.93.gov.cn/93app/data.do";//?private URL url;private HttpURLConnection urlConn;private String data = "";public String getJsonByGet(final String param){try {url = new URL(JSON_URL + param);urlConn = (HttpURLConnection) url.openConnection();//�õ�HttpsURLConnection��������urlConn.setConnectTimeout(5000);//�����������ʱ��urlConn.setReadTimeout(5000);//���ö�ȡʱ��int responseCode = urlConn.getResponseCode();//�õ���Ӧ��if(responseCode == 200){//200��ʾ��Ӧ�ɹ�InputStream inputStream = urlConn.getInputStream();//������Ӧ�����������//��ȡ���byte[] buffer = new byte[1024];int length = 0;while((length=inputStream.read(buffer)) != -1){//˵�����û�ж�ȡ��String str = new String(buffer,0,length);//���ζ�ȡ�������data += str;//�ռ����ۼӣ����}Log.d("main", data);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return data;}public String getJsonByPost(final String param){try {url = new URL(JSON_URL);urlConn = (HttpURLConnection) url.openConnection();//�õ�HttpsURLConnection��������urlConn.setConnectTimeout(5000);//�����������ʱ��urlConn.setReadTimeout(5000);//���ö�ȡʱ��//post请求的设置,与get的不同的地方urlConn.setRequestMethod("POST");//设置 为post请求urlConn.setDoInput(true);urlConn.setDoOutput(true);//把参数param设置到请求的正文中OutputStream outputStream = urlConn.getOutputStream();//得到请求的输出流,把参数输出给请求outputStream.write(param.getBytes());outputStream.flush();//刷新,推送过去int responseCode = urlConn.getResponseCode();//�õ���Ӧ��if(responseCode == 200){//200��ʾ��Ӧ�ɹ�InputStream inputStream = urlConn.getInputStream();//������Ӧ�����������//��ȡ���byte[] buffer = new byte[1024];int length = 0;while((length=inputStream.read(buffer)) != -1){//˵�����û�ж�ȡ��String str = new String(buffer,0,length);//���ζ�ȡ�������data += str;//�ռ����ۼӣ����}Log.d("main", data);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return data;}}