參考 httpClient 發送 get請求;web
客戶端示例:json
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();
}
}
}app
服務器端示例:socket
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();
}post