java原生http请求
时间: 2023-11-10 18:59:58 浏览: 39
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);
}
}
}
```