java 发送get请求_Java发送GET、POST请求代码

一、创建一个servlet来接收get或post请求

package guwen;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.io.SAXReader;

public class TestServlet extends HttpServlet{

/**

* 接收get请求

*/

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

req.setCharacterEncoding("UTF-8");

resp.setCharacterEncoding("UTF-8");

System.out.println(req.getQueryString());  //打印参数

PrintWriter out = resp.getWriter();

out.print("响应");  //响应

}

/**

* 接收post请求

*/

@Override

protected void doPost(HttpServletRequest req, IOException {

resp.setCharacterEncoding("UTF-8");

req.setCharacterEncoding("UTF-8");

System.out.println(req.getQueryString());  //打印参数

InputStream inputStream = req.getInputStream();

SAXReader reader = new SAXReader();

try {

Document document = reader.read(inputStream);  //报文体

System.out.println(document.asXML());

} catch (DocumentException e) {

e.printStackTrace();

}

PrintWriter out = resp.getWriter();

out.print("响应");  //响应

}

}

二、发送请求

package guwen;

import java.io.IOException;

import org.apache.http.HttpEntity;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClientBuilder;

import org.apache.http.util.EntityUtils;

public class ConnectionUtil {

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

//sent get

doGet("http://localhost:8088/sentTest/test?p=123");

//sent post

doPost("http://localhost:8088/sentTest/test?p=321","aa");

}

/**

* 发送get请求

* @throws IOException

*/

public static String doGet(String url) throws ClientProtocolException, IOException {

CloseableHttpClient httpClient = HttpClientBuilder.create().build();

HttpGet httpGet = new HttpGet(url);

//配置请求的超时设置

RequestConfig requestConfig = RequestConfig.custom()

.setConnectionRequestTimeout(50)

.setConnectTimeout(50)

.setSocketTimeout(50).build();

httpGet.setConfig(requestConfig);

CloseableHttpResponse response = null;

String res = null;

try {

response = httpClient.execute(httpGet);   //发送请求

System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());

HttpEntity entity = response.getEntity();

res = EntityUtils.toString(entity,"utf-8");

System.out.println(res);

} catch (ClientProtocolException e) {

throw e;

} catch (IOException e) {

throw e;

} finally{

httpGet.releaseConnection();

}

return res;

}

/**

* 发送get请求

* @throws IOException

*/

public static String doPost(String url,String body) throws IOException {

CloseableHttpClient httpclient = HttpClientBuilder.create().build();

HttpPost httpPost = new HttpPost(url);

//配置请求的超时设置

RequestConfig requestConfig = RequestConfig.custom()

.setConnectionRequestTimeout(50)

.setConnectTimeout(50)

.setSocketTimeout(50).build();

httpPost.setConfig(requestConfig);

CloseableHttpResponse response = null;

String res = null;

try {

if (body != null) {  //设置报文体 设置编码为 UTF-8

StringEntity entity = new StringEntity(body, "UTF-8");

httpPost.setEntity(entity);

}

response = httpclient.execute(httpPost);  //发送请求

System.out.println(response.toString());

HttpEntity entity = response.getEntity();

res = EntityUtils.toString(entity, "utf-8");

System.out.println(res);

} catch (ClientProtocolException e) {

throw e;

} catch (IOException e) {

throw e;

} finally{

httpPost.releaseConnection();

}

return res;

}

}

Java可以使用HttpURLConnection或者HttpClient来发送get和post请求到微信接口。以下是示例代码: 使用HttpURLConnection发送get请求: ```java URL url = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } else { System.out.println("GET request failed, response code: " + responseCode); } ``` 使用HttpURLConnection发送post请求: ```java String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // 设置post请求参数 String urlParameters = "json data..."; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } else { System.out.println("POST request failed, response code: " + responseCode); } ``` 使用HttpClient发送get请求: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"); CloseableHttpResponse response = httpClient.execute(httpGet); try { HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); System.out.println(responseBody); } finally { response.close(); } ``` 使用HttpClient发送post请求: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"); // 设置post请求参数 StringEntity entity = new StringEntity("json data...", ContentType.APPLICATION_JSON); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity, "UTF-8"); EntityUtils.consume(responseEntity); System.out.println(responseBody); } finally { response.close(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值