发送HTTP请求,HttpPost

HttpPost httpRequest = new HttpPost("url");

 List<NameValuePair> nvalues = new ArrayList<NameValuePair>();
 nvalues.add(new BasicNameValuePair("key1", value1));
 nvalues.add(new BasicNameValuePair("key2", value2));
 nvalues.add(new BasicNameValuePair("key3", value3));
 
 httpRequest.setEntity(new UrlEncodedFormEntity(nvalues));

 HttpResponse response = new DefaultHttpClient().execute(httpRequest);

 if (response.getStatusLine().getStatusCode() == 200) {// 获取调用api返回数据

//doing something
}

import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class HttpPostTest {

    public static void main(String[] args) throws IOException {

        HttpPostTest test = new HttpPostTest();
        test.post("http://localhost:8080/limiter.html");
    }

    private void post(String url) throws IOException {
        HttpPost httpRequest = new HttpPost(url);

        List<BasicNameValuePair> nvalues = new ArrayList<>();
        // 请求的参数
//        nvalues.add(new BasicNameValuePair("key1", "v1"));
//        nvalues.add(new BasicNameValuePair("key2", "v2"));
//        nvalues.add(new BasicNameValuePair("key3", "v3"));

        httpRequest.setEntity(new UrlEncodedFormEntity(nvalues));

        HttpResponse response = new DefaultHttpClient().execute(httpRequest);

        if (response.getStatusLine().getStatusCode() == 200) {// 获取调用api返回数据

                //doing something
            InputStream content = response.getEntity().getContent();
            InputStreamReader reader = new InputStreamReader(content);
            BufferedReader bufr = new BufferedReader(reader);//缓冲
            String str;
            while((str = bufr.readLine()) != null){
                System.out.println(str);
            }

        }

    }
}

需要的jar包:
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.2</version>
   <scope>test</scope>
</dependency>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值