程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> HttpClient調用 教程

HttpClient調用 教程

編輯:關於JAVA
 

package com.paic.pad.common.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/***
*
* @author YANBAOHANG502
*
*/
public class RequestUtil {

public static String post(String url, String json) {
DefaultHttpClient httpclient = new DefaultHttpClient();
String body = "{}";
HttpPost post = postForm(url, json);
body = invoke(httpclient, post);
httpclient.getConnectionManager().shutdown();
return body;
}

private static HttpPost postForm(String url, String json) {
HttpPost httpost = null;
try {
httpost = new HttpPost(url);
if (StringUtils.isNotBlank(json)) {
StringEntity input = new StringEntity(json, "utf-8");
input.setContentType("application/json");
httpost.setEntity(input);
}
} catch (Exception e) {
}
return httpost;
}

private static String invoke(DefaultHttpClient httpclient,
HttpUriRequest httpost) {
HttpResponse response = sendRequest(httpclient, httpost);
String body = paseResponse(response);
return body;
}

private static HttpResponse sendRequest(DefaultHttpClient httpclient,
HttpUriRequest httpost) {
HttpResponse response = null;
try {
response = httpclient.execute(httpost);
} catch (Exception e) {
}
return response;
}

private static String paseResponse(HttpResponse response) {
HttpEntity entity = response.getEntity();
String body = "{}";
try {
body = EntityUtils.toString(entity);
} catch (Exception e) {
}
return body;
}

}

 

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved