参考 httpClient 发送 get请求;
客户端示例:
public static void main(String[] args) {
// 第一个 sendHttpPost
HttpDemo1 httpDemo1 = new HttpDemo1();
JSONObject jsonStr = new JSONObject();
jsonStr.put("name", "httpClient Post 测试");
jsonStr.put("address", "广东深圳");
jsonStr.put("phone", "15555");
String httpUrlPost = "http://localhost:8080/web1/servletPostCallBack.hts";
String result = httpDemo1.sendHttpPost(httpUrlPost, jsonStr.toString());
System.out.println("result:" + result);
}
public String sendHttpPost(String httpUrl,String jsonStr){
String result = "";
HttpClient httpClient = null;
try{
httpClient = new DefaultHttpClient();
//设置等待读取数据超时时间 120秒
httpClient.getParams().setParameter("http.socket.timeout",2*1000*60);
//设置请求超时 30秒
httpClient.getParams().setParameter("http.connection.timeout",1*1000*30);
//创建HttpPost对象
HttpPost httpPost = new HttpPost(httpUrl);
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse httpResponse = null;
StringEntity entity = new StringEntity(jsonStr,"utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");//发送json数据需要设置contentType
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) { //请求成功响应,读取返回数据
result = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
}else{
StringBuffer errorMsg = new StringBuffer();
errorMsg.append("httpStatus:");
errorMsg.append(httpResponse.getStatusLine().getStatusCode());
errorMsg.append(httpResponse.getStatusLine().getReasonPhrase());
errorMsg.append(", Header: ");
Header[] headers = httpResponse.getAllHeaders();
for (Header header : headers){
errorMsg.append(header.getName());
errorMsg.append(":");
errorMsg.append(header.getValue());
}
}
return result;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try{
httpClient.getConnectionManager().shutdown();
}catch (Exception e){
e.printStackTrace();
}
}
}
服务器端示例:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
String strReq = null;
PrintWriter out = null;
inputStream = request.getInputStream();
inputStreamReader = new InputStreamReader(inputStream,"utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer result = new StringBuffer();
String line = null;
while((line = bufferedReader.readLine()) != null){
result.append(line);
}
//请求json报文
strReq = result.toString();
System.out.println("post请求的报文为:" + strReq);
response.setCharacterEncoding("UTF-8");
out = response.getWriter();
out.print("接受成功--this is ok!");
out.close();
}