HttpClient4.5发送post请求

HttpClient4.5发送post请求示例代码

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Test {

    public static void main(String args[]){

            String  url = "你的网址";
            // 获取当前客户端对象
            HttpClient httpClient = HttpClientBuilder.create().build();
              // 根据地址发送post请求
            HttpPost request = new HttpPost(url);
            try {

                //设置添加post数据
                List<NameValuePair> postData = new ArrayList<NameValuePair>();
                postData.add(new BasicNameValuePair("username","user"));
                postData.add(new BasicNameValuePair("password","ps"));
                request.setEntity(new UrlEncodedFormEntity(postData));

                // 通过请求对象获取响应对象
                 HttpResponse response = httpClient.execute(request);
                 //判断网络连接状态码是否正常(0--200都数正常)
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                        //获取响应实体
                        String result = EntityUtils.toString(response.getEntity(),"utf-8");
                        System.out.println(result);
                   } 



            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值