1. 程式人生 > >使用httpclient傳遞java引數呼叫http介面

使用httpclient傳遞java引數呼叫http介面

使用的Jar包:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>

程式碼:

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(); } } }