java HttpClient POST请求

Posted 不当咸鱼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
		}
    }	
}

 

以上是关于java HttpClient POST请求的主要内容,如果未能解决你的问题,请参考以下文章

Java学习心得之 HttpClient的GET和POST请求

java HttpClient POST请求

java + httpclient +post请求(记录下)

用java做一个httpClient 发送https 的get请求,需要证书验证的那种,求大神指点一下!

JAVA利用HttpClient进行POST请求(HTTPS)

Java学习之HttpClient的GET与POST请求