引用
工作中经常使用的HTTP请求方法,和大家分享下。
package com.pinkitec.core.util; import java.io.IOException; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpClientParams; import com.pinkitec.core.io.unsync.UnsyncByteArrayInputStream; public class HttpClientUtil { @SuppressWarnings("deprecation") public static JSONObject doPost(JSONObject json, String url)throws Exception{ org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.setContentChunked(true); postMethod.setRequestBody(new UnsyncByteArrayInputStream(json.toString().getBytes("UTF-8"))); HttpClientParams params = new HttpClientParams(); params.setConnectionManagerTimeout(10000L); httpClient.setParams(params); // 执行postMethod JSONObject result = null; int statusCode = 0; statusCode = httpClient.executeMethod(postMethod); // 200 if (statusCode == HttpStatus.SC_OK){ result = new JSONObject(); String str = ""; try { byte[] bytes = postMethod.getResponseBody(); str = new String(bytes, "UTF-8"); JSONObject response = JSONObject.fromObject(str); return response; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } postMethod.releaseConnection(); return result; } public static JSONObject doGet(JSONObject json, String url)throws Exception{ org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); GetMethod getMethod = new GetMethod(url); HttpClientParams params = new HttpClientParams(); params.setConnectionManagerTimeout(10000L); httpClient.setParams(params); // 执行postMethod JSONObject result = null; int statusCode = 0; statusCode = httpClient.executeMethod(getMethod); // 200 if (statusCode == HttpStatus.SC_OK){ result = new JSONObject(); String str = ""; try { byte[] bytes = getMethod.getResponseBody(); str = new String(bytes, "UTF-8"); JSONObject response = JSONObject.fromObject(str); return response; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } getMethod.releaseConnection(); return result; } public static void main(String[] args) { String[] a = new String[]{"3","1"}; System.out.println(a.clone()); System.out.println(Float.parseFloat("0.0")); } }