使用的jar包
- httpcore-4.4.4.jar
- httpclient-4.5.2.jar
- fastjson-1.2.7.jar
说明
- post方法的参数通过HttpPost的setEntity方法设置。服务器端可以通过request.getParameter(“xxx”)接收参数。
- post方法返回值为JSON对象,其中“status_code”为http状态码,“data”为请求返回的数据。
- 示例中,使用FastJson(阿里)解析JSON对象。
示例代码
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class HttpClient {
public static JSONObject post(String url, JSONObject jsonData) {
JSONObject result = new JSONObject();
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
if (jsonData != null && !jsonData.isEmpty()){
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Set<Entry<String, Object>> set = jsonData.entrySet();
for (Entry<String, Object> entry : set){
String key = entry.getKey();
String value = entry.getValue().toString();
nameValuePairs.add(new BasicNameValuePair(key, value));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
result.put("status_code", statusCode);
if (entity != null) {
result.put("data", EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
Log.logger.error("连接" + url + "失败,原因为" + e.getMessage());
} catch (ParseException e) {
Log.logger.error("连接" + url + "失败,原因为" + e.getMessage());
} catch (IOException e) {
Log.logger.error("连接" + url + "失败,原因为" + e.getMessage());
} finally {
if (response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}