码迷,mamicode.com
首页 > 编程语言 > 详细

java HttpClient POST请求

时间:2017-05-31 23:07:37      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:编码   read   encode   int   app   open   oid   ons   utils   

一个简单的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请求

标签:编码   read   encode   int   app   open   oid   ons   utils   

原文地址:http://www.cnblogs.com/dreamyu/p/6926158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!