需要用的jar包:
代码:
package http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
/**
* 发出HTTP请求,返回参数
* @param path 请求路径
* @param map 请求参数
* @param encode 编码
* @return 服务器返回参数
*/
public static String sendHttpClientPost(String path,Map<String,String> map,String encode){
List<NameValuePair> list = new ArrayList<NameValuePair>();
//封装请求参数
if(map != null && !map.isEmpty()){
for(Map.Entry<String, String> entry : map.entrySet()){
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
//将请求参数封装到表单中,并设置编码
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,encode);
//根据URL创建POST请求对象
HttpPost httpPost = new HttpPost(path);
//设置请求参数
httpPost.setEntity(entity);
//得到默认提交方式,提交请求
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
//判断服务器响应码 200代表请求成功
if(response.getStatusLine().getStatusCode() == 200){
return changeInputStream(response.getEntity().getContent(), encode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* 将输入流中数据转换为String
* @param inputStream 输入流对象
* @param encode 编码
* @return 流信息
*/
public static String changeInputStream(InputStream inputStream,String encode){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte [] data = new byte[1024];
int len = 0;
String result = "";
if(inputStream != null){
try {
while((len = inputStream.read(data)) != -1){
outputStream.write(data, 0, len);
}
result = new String(outputStream.toByteArray(),encode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "http://localhost:8080/test/user/login";
Map<String,String> map = new HashMap<String,String>();
map.put("userName", "admin");
map.put("psssword", "123456");
String result = sendHttpClientPost(path, map, "utf-8");
System.out.println(result);
}
}