注:在上一个java.34工程中建类,才能使用apche库
代码:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class TestPost {
public static void main(String[] args) {
// 网络读写接口,来自有道翻译
// http://fanyi.youdao.com/openapi.do?
// keyfrom=CLP-test&key=1870425496&type=data&doctype=xml&version=1.1&q=welcome
new Post().start();
}
}
class Post extends Thread {
HttpClient client = HttpClients.createDefault();
public void run() {
HttpPost post = new HttpPost("http://fanyi.youdao.com/openapi.do?");
try {
// keyfrom=CLP-test&key=1870425496&type=data&doctype=xml&version=1.1&q=welcome
List<BasicNameValuePair> parameters = new ArrayList<>();
// 所有entity键值对
parameters.add(new BasicNameValuePair("keyfrom", "CLP-test"));
parameters.add(new BasicNameValuePair("key", "1870425496"));
parameters.add(new BasicNameValuePair("type", "data"));
parameters.add(new BasicNameValuePair("doctype", "xml"));
parameters.add(new BasicNameValuePair("version", "1.1"));
parameters.add(new BasicNameValuePair("q", "welcome"));
post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
// client.execute(post)之前,需要为post指定提交的数据
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
System.out.println(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果: