java设置http参数_java-如何在HttpPos中使用参数

如果您想传递一些http参数并发送json请求,也可以使用这种方法:

(注意:我添加了一些额外的代码,以防万一它对将来的其他读者有所帮助)

public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {

//add the http parameters you wish to pass

List postParameters = new ArrayList<>();

postParameters.add(new BasicNameValuePair("param1", "param1_value"));

postParameters.add(new BasicNameValuePair("param2", "param2_value"));

//Build the server URI together with the parameters you wish to pass

URIBuilder uriBuilder = new URIBuilder("http://google.ug");

uriBuilder.addParameters(postParameters);

HttpPost postRequest = new HttpPost(uriBuilder.build());

postRequest.setHeader("Content-Type", "application/json");

//this is your JSON string you are sending as a request

String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";

//pass the json string request in the entity

HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));

postRequest.setEntity(entity);

//create a socketfactory in order to use an http connection manager

PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();

Registry connSocketFactoryRegistry = RegistryBuilder.create()

.register("http", plainSocketFactory)

.build();

PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);

connManager.setMaxTotal(20);

connManager.setDefaultMaxPerRoute(20);

RequestConfig defaultRequestConfig = RequestConfig.custom()

.setSocketTimeout(HttpClientPool.connTimeout)

.setConnectTimeout(HttpClientPool.connTimeout)

.setConnectionRequestTimeout(HttpClientPool.readTimeout)

.build();

// Build the http client.

CloseableHttpClient httpclient = HttpClients.custom()

.setConnectionManager(connManager)

.setDefaultRequestConfig(defaultRequestConfig)

.build();

CloseableHttpResponse response = httpclient.execute(postRequest);

//Read the response

String responseString = "";

int statusCode = response.getStatusLine().getStatusCode();

String message = response.getStatusLine().getReasonPhrase();

HttpEntity responseHttpEntity = response.getEntity();

InputStream content = responseHttpEntity.getContent();

BufferedReader buffer = new BufferedReader(new InputStreamReader(content));

String line;

while ((line = buffer.readLine()) != null) {

responseString += line;

}

//release all resources held by the responseHttpEntity

EntityUtils.consume(responseHttpEntity);

//close the stream

response.close();

// Close the connection manager.

connManager.close();

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值