使用httpclient传递java参数调用http接口

使用的Jar包:


org.apache.httpcomponents
httpclient
4.3.5

代码:

public class HttpClientTest {

    public static void main(String[] args){
        String reqUrl = "http://ip:port/context/url";
        JSONObject paramJson=new JSONObject();
        paramJson.put("jbEmp","wangzc");
        paramJson.put("startDate","20140908");
        paramJson.put("endDate","20140909");

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost=new HttpPost(reqUrl);
        httpPost.addHeader("Content-Type","application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(paramJson.toString(), Charset.forName("UTF-8")));
        try {
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed:" + response.getStatusLine());
            }else{
                String resultStr = EntityUtils.toString(response.getEntity());
                JSONObject resultJSON=JSONObject.fromObject(resultStr);
                System.out.println("resultJSON:"+resultJSON);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(使用httpclient传递java参数调用http接口)