java35.HTTP通信------使用HttpClient进行Post方式通信

注:在上一个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();
        }
    }
}

运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值