Java发送application/x-www-form-urlencoded
时间: 2023-07-15 16:11:34 浏览: 124
要发送`application/x-www-form-urlencoded`类型的数据,可以使用Java中的`HttpURLConnection`类或者使用Apache的`HttpClient`库。
使用`HttpURLConnection`类:
```java
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
String data = "param1=value1¶m2=value2";
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
os.flush();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
System.out.println(response.toString());
} else {
System.out.println("Error: " + responseCode);
}
```
使用Apache的`HttpClient`库:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println(result);
} else {
System.out.println("Error: " + response.getStatusLine().getStatusCode());
}
httpClient.close();
```
阅读全文