我用的httpclient是4.3版本
需要下载以下包:httpclient-4.3.3.jar,httpcore-4.3.2.jar。下面是post数据到远端,并读取返回内容。
package httputil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.ClientProtocolException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
public final class HttpUtil {
private CloseableHttpClient httpClient;
private HttpPost httpPost;
public void doPost(String jsonString) throws ClientProtocolException,
IOException {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("http://192.168.1.218/");
List <NameValuePair> data = new ArrayList <NameValuePair>();
data.add(new BasicNameValuePair("message", jsonString));
httpPost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse httpResponse = httpClient.execute(httpPost);
int httpCode = httpResponse.getStatusLine().getStatusCode();
if (httpCode == HttpURLConnection.HTTP_OK && httpResponse != null) {
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream,"UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader);// 读字符串用的。
String s;
while (((s = reader.readLine()) != null)) {
System.out.println(s);
}
reader.close();// 关闭输入流
} else {
}
}
public static void main(String[] args) throws ClientProtocolException,
IOException {
long taskid = 111L;
String tableName = "sqltable";
JSONObject jsonStatus = new JSONObject();
jsonStatus.put("code", 0);
jsonStatus.put("msg", "succ");
// ===========================
JSONObject jsonData = new JSONObject();
jsonData.put("taskid", taskid);
jsonData.put("tableName", tableName);
// ===========================
JSONObject objData = new JSONObject();
objData.put("status", jsonStatus);
objData.put("data", jsonData);
HttpUtil http = new HttpUtil();
http.doPost(objData.toString());
}
}
httpclient4.3和以前的变化较大,很多以前的例子都不能用了。另外下面这段代码就post不成功,没找到原因。(对照上面代码)
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("http://192.168.1.218/");
// List <NameValuePair> data = new ArrayList <NameValuePair>();
// data.add(new BasicNameValuePair("message", jsonString));
StringEntity data=new StringEntity(jsonString);
httpPost.setEntity(data);
HttpResponse httpResponse = httpClient.execute(httpPost);