java HttpClient POST请求

一个简单的HttpClient POST 请求实例

package com.httpclientget;

import java.awt.List;
import java.util.ArrayList;

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;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;


public class TestPost {

	public static void main(String[] args) {

		CreatHttpUrl creatUrl = new CreatHttpUrl();
		String urlStr = "https://openapi.youdao.com/api";
		String paramStr = creatUrl.createParam("good","en","zh-CHS");
		
		System.out.println(paramStr);
		
		new Post().start();
	}

}
class Post extends Thread
{
	HttpClient client = HttpClients.createDefault();
     @Override
    public void run() {
         HttpPost post = new HttpPost("https://openapi.youdao.com/api");
    	 try {
    		 //post要提交的参数
    		 ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    		 params.add(new BasicNameValuePair("q", "good")); 
    		 params.add(new BasicNameValuePair("salt", "1496238482428")); 
    		 params.add(new BasicNameValuePair("sign", "02E15CDAF871B698FE04EE32FD2CF155")); 
    		 params.add(new BasicNameValuePair("from", "en")); 
    		 params.add(new BasicNameValuePair("appKey", "7743eee7f7e11d75")); 
    		 params.add(new BasicNameValuePair("to", "zh-CHS")); 
    		 
             //设置提交编码
             post.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
             //创建response接收返回值
             HttpResponse response = client.execute(post);
             HttpEntity entity = response.getEntity();
             String result = EntityUtils.toString(entity,"UTF-8");

             System.out.print(result);
		} catch (Exception e) {

		     e.printStackTrace();
		}
    }	
}

 

posted @ 2017-05-31 22:14  不当咸鱼  阅读(2956)  评论(0编辑  收藏  举报