Java发送HTTP的get,post请求(JSON)

  1 import net.sf.json.JSONObject;
  2 import org.apache.commons.httpclient.*;
  3 import org.apache.commons.httpclient.methods.GetMethod;
  4 import org.apache.commons.httpclient.params.HttpMethodParams;
  5 import org.apache.http.HttpEntity;
  6 import org.apache.http.HttpResponse;
  7 import org.apache.http.client.methods.HttpPost;
  8 import org.apache.http.entity.StringEntity;
  9 import org.apache.http.impl.client.DefaultHttpClient;
 10 import org.apache.http.util.EntityUtils;
 11 import java.io.IOException;
 12 
 13 /**
 14  * Created by liqun.chen on 2017/5/15.
 15  */
 16 public class HttpUtil {
 17     /**
 18      * json 字符串
 19      * @param url
 20      * @param param
 21      * @return
 22      */
 23     public static String getSerchPersion(String url,String param){
 24       /* 1 生成 HttpClinet 对象并设置参数 */
 25         HttpClient httpClient = new HttpClient();
 26         // 设置 Http 连接超时为5秒
 27         httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
 28       /* 2 生成 GetMethod 对象并设置参数 */
 29         GetMethod getMethod = new GetMethod(url);
 30         // 设置 get 请求超时为 5 秒
 31         getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
 32         // 设置请求重试处理,用的是默认的重试处理:请求三次
 33         getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
 34         String response = "";
 35       /* 3 执行 HTTP GET 请求 */
 36         try {
 37             int statusCode = httpClient.executeMethod(getMethod);
 38          /* 4 判断访问的状态码 */
 39             if (statusCode != HttpStatus.SC_OK) {
 40                 System.err.println("请求出错: "+ getMethod.getStatusLine());
 41             }
 42          /* 5 处理 HTTP 响应内容 */
 43             // HTTP响应头部信息,这里简单打印
 44             Header[] headers = getMethod.getResponseHeaders();
 45             for (Header h : headers)
 46                 System.out.println(h.getName() + "------------ " + h.getValue());
 47             // 读取 HTTP 响应内容,这里简单打印网页内容
 48             byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
 49             response = new String(responseBody, param);
 50             System.out.println("----------response:" + response);
 51             // 读取为 InputStream,在网页内容数据量大时候推荐使用
 52             // InputStream response = getMethod.getResponseBodyAsStream();
 53         } catch (HttpException e) {
 54             // 发生致命的异常,可能是协议不对或者返回的内容有问题
 55             System.out.println("请检查输入的URL!");
 56             e.printStackTrace();
 57         } catch (IOException e) {
 58             // 发生网络异常
 59             System.out.println("发生网络异常!");
 60             e.printStackTrace();
 61         } finally {
 62          /* 6 .释放连接 */
 63             getMethod.releaseConnection();
 64         }
 65         return response;
 66     }
 67     /**
 68      * post请求
 69      * @param url
 70      * @param json
 71      * @return
 72      */
 73     public static JSONObject doPost(String url,JSONObject json){
 74         DefaultHttpClient client = new DefaultHttpClient();
 75         HttpPost post = new HttpPost(url);
 76         JSONObject response = null;
 77         try {
 78             StringEntity s = new StringEntity(json.toString());
 79             s.setContentEncoding("UTF-8");
 80             s.setContentType("application/json");//发送json数据需要设置contentType
 81             post.setEntity(s);
 82             HttpResponse res = client.execute(post);
 83             if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
 84                 HttpEntity entity = res.getEntity();
 85                 String result = EntityUtils.toString(res.getEntity());// 返回json格式:
 86                 response = JSONObject.fromObject(result);
 87             }
 88         } catch (Exception e) {
 89             throw new RuntimeException(e);
 90         }
 91         return response;
 92     }
 1 //调用
 2 public static void main(String arg[]) throws Exception {
 3         String url = "http://localhost:8080/";
 4         JSONObject params = new JSONObject();
 5         params.put("personName", "name");
 6         params.put("personCode", "230882xxxxxx2116");
 7         JSONObject param2 = new JSONObject();
 8         param2.put("pageNo", 1);
 9         param2.put("pageSize", 20);
10         params.put("page", param2);
11         String param = "q="+params.toString();
12         //get 请求
13         String ret = getSerchPersion(url, param.toString());
14         System.out.println(ret);
15 //        JSONObject jsonResponse=JSONObject.fromObject(param);
16 //        JSONObject json = (JSONObject)jsonResponse.get("page");
17 //        System.out.println(json.get("pageSize"));
18 
19         //post 请求
20         JSONObject jsonObject = doPost(url,params);
21         System.out.println(jsonObject.toString());
22     }

 

posted @ 2017-06-06 15:09  Mr..Chen  阅读(45144)  评论(2编辑  收藏  举报