httpClient发起get、post请求

发起get请求,参数带在url后面

private String getResult(String url) throws MicroRunTimeException {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            BasicResponseHandler responseHandler = new BasicResponseHandler();
            return httpClient.execute(httpGet, responseHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

发起post请求,content_typeapplication/json时:

private String postResult(String url, Map<String, String> paramMap) throws MicroRunTimeException {
        try {
            String jsonData = JSON.toJSONString(paramMap);
            Response response = Request.Post(url)
                    .addHeader(CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF_8)
                    .bodyByteArray(jsonData.getBytes()) //注意,此处是传递json格式参数
                    .socketTimeout(OUT_TIME)
                    .connectTimeout(CONNECT_TIMEOUT)
                    .execute();
            String content = response.returnContent().asString();
            return content;
        }catch (Exception e) {
             e.printStackTrace();
        }
    }

发起post请求,content_typeapplication/x-www-form-urlencoded时:

public String postResultFForm(String url, Map<String, String> paramMap) throws MicroRunTimeException {
        Form form = Form.form();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            form.add(entry.getKey(), entry.getValue());
        }
        try {
            Content content = Request.Post(url)
                    .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED_UTF_8)
                    .bodyForm(form.build(), allCharset).socketTimeout(OUT_TIME).connectTimeout(CONNECT_TIMEOUT).execute().returnContent();
            return content.asString();
        } catch (Exception e) {
             e.printStackTrace();
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容