Java实现原生http请求
时间: 2023-04-11 17:01:37 浏览: 102
Java可以使用HttpURLConnection或者HttpClient来实现原生的http请求。其中HttpURLConnection是Java自带的类,HttpClient则需要导入相关的jar包。具体实现可以参考Java官方文档或者相关的教程。
相关问题
java原生http请求
Java原生HTTP请求可以使用OkHttp或CloseableHttpClient来实现。使用OkHttp需要引入okhttp-3.10.0.jar的依赖,使用CloseableHttpClient则需要引入httpclient-4.5.6.jar的依赖。以下是一个使用OkHttp进行HTTP请求的示例代码:
```java
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HttpTest {
public static void main(String[] args) throws IOException {
String url = "http://10.30.10.151:8012/gateway.do";
OkHttpClient client = new OkHttpClient();
Map<String, String> paraMap = new HashMap<>();
paraMap.put("yybh", "1231231");
RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart("consumerAppId", "tst")
.addFormDataPart("serviceName", "queryCipher")
.addFormDataPart("params", JSON.toJSONString(paraMap))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = client
.newCall(request)
.execute();
if (response.isSuccessful()) {
System.out.println("result: " + response.body().string());
} else {
throw new IOException("Unexpected code " + response);
}
}
}
```
javahttp原生请求方式
Java 原生提供了多种方式进行 HTTP 请求,包括:
1. 使用 URLConnection 类进行请求,示例代码如下:
```
URL url = new URL("http://www.example.com");
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("request body");
out.close();
InputStream response = connection.getInputStream();
```
2. 使用 HttpURLConnection 类进行请求,示例代码如下:
```
URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("request body");
out.close();
InputStream response = connection.getInputStream();
```
3. 使用 HttpClient 类进行请求,示例代码如下:
```
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com");
httpPost.setHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity("request body");
httpPost.setEntity(entity);
CloseableHttpResponse response = client.execute(httpPost);
```
以上是 HTTP POST 请求的示例代码,HTTP GET 请求的代码类似,只需要修改请求方法即可。