您的位置:首页 > 理论基础 > 计算机网络

Http进行网络通信

2016-07-13 14:45 537 查看
http使用get的方式进行网络通信:

package com.testClientPost;

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;

/**
* 使用HttpClient进行Post方式通信
* @author Administrator
*
*/
public class TestPost {
public static void main(String[] args) {
//http://fanyi.youdao.com/openapi.do
//keyfrom=guodaxia&key=1142217390&type=data&doctype=xml&version=1.1&q=welcome
new Post().start();
}
}
class Post extends Thread{
HttpClient client=HttpClients.createDefault();

@Override
public void run() {
HttpPost post=new HttpPost("http://fanyi.youdao.com/openapi.do");
try {
//Post需要请求参数
//keyfrom=guodaxia&key=1142217390&type=data&doctype=xml&version=1.1&q=welcome
List<BasicNameValuePair> parameters=new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("keyfrom", "guodaxia"));
parameters.add(new BasicNameValuePair("key", "1142217390"));
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"));
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();
}
}
}


View Code
注意:

我这里使用的httpClient是4.3.5版本的

有道翻译api信息在我的邮箱中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: