1、使用HttpClient执行Get和Post
相关文档:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e37
1)执行GET请求
public static MapsendGet(String sendUrl) {Map mres = new HashMap ();// 默认配置创建一个httpClient实例CloseableHttpClient httpClient = HttpClients.createDefault();// 创建httpGet远程连接实例HttpGet httpGet = new HttpGet(sendUrl);// 设置配置请求参数RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间.setConnectionRequestTimeout(35000)// 请求超时时间.setSocketTimeout(60000)// 数据读取超时时间.build();// 为httpGet实例设置配置httpGet.setConfig(requestConfig);try {// 执行get请求得到返回对象CloseableHttpResponse response = httpClient.execute(httpGet);// 通过返回对象获取返回数据HttpEntity entity = response.getEntity();// 通过EntityUtils中的toString方法将结果转换为字符串String result = EntityUtils.toString(entity, "UTF-8");mres = (Map ) JSONObject.toBean(JSONObject.fromObject(result), Map.class);} catch (Exception e) {e.printStackTrace();} finally {// 关闭资源if (null != httpClient) {try {httpClient.close();} catch (Exception e) {e.printStackTrace();}}}return mres; }
2)执行Post请求
/* * Create the POST request */HttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost("http://example.com/");// Request parameters and other properties.Listparams = new ArrayList ();params.add(new BasicNameValuePair("user", "Bob"));try { httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));} catch (UnsupportedEncodingException e) { // writing error to Log e.printStackTrace();}/* * Execute the HTTP Request */try { HttpResponse response = httpClient.execute(httpPost); HttpEntity respEntity = response.getEntity(); if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); }} catch (ClientProtocolException e) { // writing exception to log e.printStackTrace();} catch (IOException e) { // writing exception to log e.printStackTrace();}
2、使用HttpURLConnection执行Get和Post
1)执行Get请求
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 返回结果-字节输入流转换成字符输入流,控制台输出字符
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
2)执行Post请求
String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData, "UTF-8" );
URL u = new URL("http://www.example.com/page.php")
;
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());
3、使用Request执行Get和Post请求
1)执行Get请求
Request.Get("http://somehost/"
)
.connectTimeout(1000)
.socketTimeout(1000)
.execute().returnContent().asString();
2)执行Post请求
Request.Post("http://www.example.com/page.php"
)
.bodyForm(Form.form().add("id", "10").build())
.execute()
.returnContent();
相关文档:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html