HttpClientの3系から4系にする時の変更方法です。
POSTメソッドを使用してパラメータとともにJSONをリクエストとして送っています。
HttpClient 3系
String myUrl = "http://XXXXXXX"; HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.connection.timeout", 5000); httpClient.getParams().setParameter("http.socket.timeout", 3000); PostMethod postMethod = new PostMethod(myUrl); postMethod.addRequestHeader("Content-Type", "application/javascript"); postMethod.addParameter("req", "1"); postMethod.addParameter("callback", "1"); JSONObject jsonObject = new JSONObject(); JSONObject context = new JSONObject(); context.put("country", "JP"); context.put("language", "ja"); jsonObject.put("context", context); postMethod.setRequestEntity(new StringRequestEntity( jsonObject.toString(), "application/javascript", "UTF-8")); httpClient.executeMethod(postMethod); String result = postMethod.getResponseBodyAsString(); JSONObject fromObject = JSONObject.fromObject(result);
これを書き換えると以下のようになります。
HttpClient 4系
String myUrl = "http://XXXXXXX"; RequestConfig requestConfig = RequestConfig .custom() .setConnectTimeout(5000) .setSocketTimeout(3000) .build(); HttpClient httpClient = HttpClientBuilder .create() .setDefaultRequestConfig(requestConfig) .build(); List<NameValuePair> requestParams = new ArrayList<NameValuePair>(); requestParams.add(new BasicNameValuePair("req", "1")); requestParams.add(new BasicNameValuePair("callback", "1")); URIBuilder builder = new URIBuilder(myUrl); builder.setParameters(requestParams); HttpPost postMethod = new HttpPost(builder.build()); postMethod.addHeader("Content-Type", "application/javascript"); JSONObject jsonObject = new JSONObject(); JSONObject context = new JSONObject(); context.put("country", "JP"); context.put("language", "ja"); jsonObject.put("context", context); StringEntity postEntity = new StringEntity(jsonObject.toString(), "UTF-8"); postEntity.setContentType("application/javascript"); postMethod.setEntity(postEntity); HttpResponse response = httpClient.execute(postMethod); String result = EntityUtils.toString(response.getEntity()); JSONObject fromObject = JSONObject.fromObject(result);
参考
パラメータの渡し方の変更方法
http://stackoverflow.com/questions/22038957/httpclient-getparams-deprecated-what-should-i-use-instead
http://stackoverflow.com/questions/12059278/how-to-post-json-request-using-apache-httpclient
レスポンスボディの受け取り方
http://stackoverflow.com/questions/14024625/how-to-get-httpclient-returning-status-code-and-response-body
JSONリクエストをPOSTする方法
http://qiita.com/yukiko-kato-bass/items/092e30bea021286d0348
3系と4系の書き換え方
https://developer.salesforce.com/page/JP:Getting_Started_with_the_Force.com_REST_API
https://developer.salesforce.com/page/JP:DemoREST.java