JAVA 客户端HTTP请求

GET请求

    public static String sendRequestWithHttpClient(String url, String jason) {
        String response = null;
        //用HttpClient发送请求,分为五步
        //第一步:创建HttpClient对象
        HttpClient httpCient = new DefaultHttpClient();
        //第二步:创建代表请求的对象,参数是访问的服务器地址
        HttpPost httpPost = new HttpPost(url + jason);

        try {
            //第三步:执行请求,获取服务器发还的相应对象
            HttpResponse httpResponse = httpCient.execute(httpPost);
            //第四步:检查相应的状态是否正常:检查状态码的值是200表示正常
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                //第五步:从相应对象当中取出数据,放到entity当中
                HttpEntity entity = httpResponse.getEntity();
                //将entity当中的数据转换为字符串
                response = EntityUtils.toString(entity, "utf-8");
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return response;
    }

POST请求:

    public static String postStringEntity(String url, JSONObject body) throws IOException {
        HttpClient httpClient = HttpUtil.genHttpClient();
        HttpPost post = new HttpPost(url);
        //这里json千万不要encode,否则会解析不出来
        StringEntity entity = new StringEntity(body.toString(), "UTF-8");  
        HttpContext context = new BasicHttpContext();
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post, context);
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        return result;
    }

 

jar包下载:

http://note.youdao.com/noteshare?id=125a5f56afa958b29035c3611dce04fa

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值