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 postData = new ArrayList();
                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();
            }
    }

}

你可能感兴趣的:(java)