miduo_login/src/main/java/com/ljsd/util/HttpUtils.java

46 lines
1.6 KiB
Java
Raw Normal View History

2019-07-01 11:27:00 +08:00
package com.ljsd.util;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtils {
public static String doPost(String url, Map<String,String> parms) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps =getFromMap(parms);
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
HttpEntity entity = response2.getEntity();
return EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
response2.close();
}
}
public static List<NameValuePair> getFromMap(Map<String,String> parms){
List<NameValuePair> nvps = new ArrayList<NameValuePair>(parms.size());
for(Map.Entry<String,String> item : parms.entrySet()){
nvps.add(new BasicNameValuePair(item.getKey(), item.getValue()));
}
return nvps;
}
}