在Java中发送HTTP POST请求
让我们假设这个URL在Java中发送HTTP POST请求,java,http,post,Java,Http,Post,让我们假设这个URL http://www.example.com/page.php?id=10 (此处需要在POST请求中发送id) 我想将id=10发送到服务器的page.php,它通过POST方法接受它 如何在Java中实现这一点 我试过这个: URL aaa = new URL("http://www.example.com/page.php"); URLConnection ccc = aaa.openConnection(); 但是我仍然不知道如何通过PO
http://www.example.com/page.php?id=10
(此处需要在POST请求中发送id)
我想将id=10
发送到服务器的page.php
,它通过POST方法接受它
如何在Java中实现这一点
我试过这个:
URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();
但是我仍然不知道如何通过POST调用
HttpURLConnection.setRequestMethod(“POST”)
和HttpURLConnection.setDoOutput(true)发送它
实际上只需要后者,因为POST随后成为默认方法。调用HttpURLConnection.setRequestMethod(“POST”)
和HttpURLConnection.setDoOutput(true)代码>实际上只需要后者,因为POST随后成为默认方法。更新答案:
String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData, "UTF-8" );
URL u = new URL("http://www.example.com/page.php");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());
由于原始答案中的某些类在较新版本的ApacheHTTP组件中被弃用,因此我发布了此更新
顺便说一下,您可以访问完整的文档以获取更多示例
有关更多信息,请查看此url:更新的答案:
由于原始答案中的某些类在较新版本的ApacheHTTP组件中被弃用,因此我发布了此更新
顺便说一下,您可以访问完整的文档以获取更多示例
有关更多信息,请查看此url:第一个答案很好,但我必须添加try/catch以避免Java编译器错误。
此外,我还很难理解如何使用Java库读取HttpResponse
以下是更完整的代码:
/*
* Create the POST request
*/
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
/*
*创建POST请求
*/
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://example.com/");
//请求参数和其他属性。
List params=new ArrayList();
添加参数(新的BasicNameValuePair(“用户”、“Bob”);
试一试{
setEntity(新的UrlEncodedFormEntity(参数,“UTF-8”);
}捕获(不支持的编码异常e){
//将错误写入日志
e、 printStackTrace();
}
/*
*执行HTTP请求
*/
试一试{
HttpResponse response=httpClient.execute(httpPost);
HttpEntity respEntity=response.getEntity();
if(respEntity!=null){
//EntityUtils以获取响应内容
字符串内容=EntityUtils.toString(respEntity);
}
}捕获(客户端协议例外e){
//将异常写入日志
e、 printStackTrace();
}捕获(IOE异常){
//将异常写入日志
e、 printStackTrace();
}
第一个答案很好,但我必须添加try/catch以避免Java编译器错误。
此外,我还很难理解如何使用Java库读取HttpResponse
以下是更完整的代码:
/*
* Create the POST request
*/
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
/*
*创建POST请求
*/
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://example.com/");
//请求参数和其他属性。
List params=new ArrayList();
添加参数(新的BasicNameValuePair(“用户”、“Bob”);
试一试{
setEntity(新的UrlEncodedFormEntity(参数,“UTF-8”);
}捕获(不支持的编码异常e){
//将错误写入日志
e、 printStackTrace();
}
/*
*执行HTTP请求
*/
试一试{
HttpResponse response=httpClient.execute(httpPost);
HttpEntity respEntity=response.getEntity();
if(respEntity!=null){
//EntityUtils以获取响应内容
字符串内容=EntityUtils.toString(respEntity);
}
}捕获(客户端协议例外e){
//将异常写入日志
e、 printStackTrace();
}捕获(IOE异常){
//将异常写入日志
e、 printStackTrace();
}
使用Apache HTTP组件的简单方法是
Request.Post("http://www.example.com/page.php")
.bodyForm(Form.form().add("id", "10").build())
.execute()
.returnContent();
请看一下使用ApacheHTTP组件的简单方法是
Request.Post("http://www.example.com/page.php")
.bodyForm(Form.form().add("id", "10").build())
.execute()
.returnContent();
看一看在vanilla Java中发送POST请求很容易。从URL
开始,我们不需要使用URL.openConnection()将其转换为URLConnection
代码>。之后,我们需要将其强制转换为HttpURLConnection
,以便访问其setRequestMethod()
方法来设置我们的方法。我们最后说,我们将通过连接发送数据
URL=新URL(“https://www.example.com/login");
URLConnection con=url.openConnection();
HttpURLConnection http=(HttpURLConnection)con;
http.setRequestMethod(“POST”);//看跌期权是另一个有效的选择
http.setDoOutput(true);
然后,我们需要说明我们将发送什么:
发送简单表单
来自http表单的普通POST具有一种格式。我们需要将输入转换为以下格式:
Map参数=newhashmap();
参数。put(“用户名”、“根”);
参数。put(“密码”,“sjh76HSn!”);//这显然是一个假密码
细木工sj=新细木工(&);
for(Map.Entry:arguments.entrySet())
sj.add(URLEncoder.encode(entry.getKey(),“UTF-8”)+“=”
+encode(entry.getValue(),“UTF-8”);
byte[]out=sj.toString().getBytes(StandardCharsets.UTF_8);
int长度=out.length;
然后,我们可以使用适当的头将表单内容附加到http请求并发送它
http.setFixedLengthStreamingMode(长度);
http.setRequestProperty(“内容类型”,“应用程序/x-www-form-urlencoded;字符集=UTF-8”);
http.connect();
尝试(OutputStream os=http.getOutputStream()){
o.写(出);
}
//使用http.getInputStream()执行一些操作
发送JSON
我们还可以使用java发送json,这也很简单:
byte[]out=“{\”用户名\“:\”根\“,\”密码\“:\”密码\“}”。getBytes(StandardCharsets.UTF\u 8);
int长度=out.length;
http.setFixedLengthStreamingMode(长度);
setRequestProperty(“内容类型”,“应用程序/json;字符集=UTF-8”);
http.connect();
尝试(OutputStream os=http.getOutputStream()){
o.写(出);
}
//使用http.getInputStream()执行一些操作
请记住,不同的服务器接受不同的json内容类型,请参阅问题
<
String postURL = "http://www.example.com/page.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(ent);
HttpClient client = new DefaultHttpClient();
HttpResponse responsePOST = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(responsePOST.getEntity().getContent()), 2048);
if (responsePOST != null) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(" line : " + line);
sb.append(line);
}
String getResponseString = "";
getResponseString = sb.toString();
//use server output getResponseString as string value.
}
HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();
public void send(){
String response = httpRequest.execute("id", "10").get();
}