本文翻译自:How to send HTTP request in java? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
In Java, How to compose a HTTP request message and send it to a HTTP WebServer? 在Java中,如何编写HTTP请求消息并将其发送到HTTP WebServer?
#1楼
参考:https://stackoom.com/question/5hiT/如何在Java中发送HTTP请求-重复
#2楼
This will help you. 这将为您提供帮助。 Don't forget to add the JAR HttpClient.jar
to the classpath. 不要忘记将JAR HttpClient.jar
添加到类路径。
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class MainSendRequest {
static String url =
"http://localhost:8080/HttpRequestSample/RequestSend.jsp";
public static void main(String[] args) {
//Instantiate an HttpClient
HttpClient client = new HttpClient();
//Instantiate a GET HTTP method
PostMethod method = new PostMethod(url);
method.setRequestHeader("Content-type",
"text/xml; charset=ISO-8859-1");
//Define name-value pairs to set into the QueryString
NameValuePair nvp1= new NameValuePair("firstName","fname");
NameValuePair nvp2= new NameValuePair("lastName","lname");
NameValuePair nvp3= new NameValuePair("email","email@email.com");
method.setQueryString(new NameValuePair[]{nvp1,nvp2,nvp3});
try{
int statusCode = client.executeMethod(method);
System.out.println("Status Code = "+statusCode);
System.out.println("QueryString>>> "+method.getQueryString());
System.out.println("Status Text>>>"
+HttpStatus.getStatusText(statusCode));
//Get data as a String
System.out.println(method.getResponseBodyAsString());
//OR as a byte array
byte [] res = method.getResponseBody();
//write to file
FileOutputStream fos= new FileOutputStream("donepage.html");
fos.write(res);
//release connection
method.releaseConnection();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
#3楼
You can use java.net.HttpUrlConnection . 您可以使用java.net.HttpUrlConnection 。
Example ( from here ), with improvements. 示例( 从此处开始 ),进行了改进。 Included in case of link rot: 包括在链接腐烂的情况下:
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
#4楼
From Oracle's java tutorial 来自Oracle的Java教程
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
#5楼
I know others will recommend Apache's http-client, but it adds complexity (ie, more things that can go wrong) that is rarely warranted. 我知道其他人会推荐Apache的http-client,但是它增加了复杂性(即,更多可能出错的东西),这是很少需要的。 For a simple task, java.net.URL
will do. 对于一个简单的任务,可以使用java.net.URL
。
URL url = new URL("http://www.y.com/url");
InputStream is = url.openStream();
try {
/* Now read the retrieved document from the stream. */
...
} finally {
is.close();
}
#6楼
Apache HttpComponents . Apache HttpComponents 。 The examples for the two modules - HttpCore and HttpClient will get you started right away. 这两个模块的示例-HttpCore和HttpClient将立即使您入门。
Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. 并不是说HttpUrlConnection是一个糟糕的选择,HttpComponents会将许多繁琐的编码抽象掉。 I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. 如果您确实想以最少的代码支持许多HTTP服务器/客户端,我将建议您这样做。 By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc. 顺便说一下,HttpCore可以用于功能最少的应用程序(客户端或服务器),而HttpClient可以用于需要支持多种身份验证方案,cookie支持等的客户端。