在Java中,如何编写HTTP请求消息并将其发送到HTTP WebServer?
如何在Java中发送HTTP请求?[重复]
您可以像这样使用Socket
String host = "www.yourhost.com";
Socket socket = new Socket(host, 80);
String request = "GET / HTTP/1.0\r\n\r\n";
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();
InputStream is = socket.getInputStream();
int ch;
while( (ch=is.read())!= -1)
System.out.print((char)ch);
socket.close();
Google Java http客户端对HTTP请求具有不错的API。您可以轻松地添加JSON支持等。尽管对于简单的请求而言,这可能会过分杀伤。
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import java.io.InputStream;
public class Network {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
System.out.println(response.getStatusCode());
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
}
这将为您提供帮助。不要忘记将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();
}
}
}
Apache HttpComponents。这两个模块的示例-HttpCore和HttpClient将立即使您入门。
并不是说HttpUrlConnection是一个不好的选择,HttpComponents会将许多繁琐的编码抽象掉。如果您确实想以最少的代码支持许多HTTP服务器/客户端,我会建议您这样做。顺便说一下,HttpCore可以用于功能最少的应用程序(客户端或服务器),而HttpClient则用于需要支持多种身份验证方案,cookie支持等的客户端。
我知道其他人会推荐Apache的http-client,但是它增加了很少需要的复杂性(例如,更多可能出错的东西)。对于一个简单的任务,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();
}
这是完整的Java 7程序:
class GETHTTPResource {
public static void main(String[] args) throws Exception {
try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://tools.ietf.org/rfc/rfc768.txt").openStream())) {
System.out.println(s.useDelimiter("\\A").next());
}
}
}
新的try-with-resources将自动关闭Scanner,这将自动关闭InputStream。
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();
}
}
有一个关于发送POST请求有很大的联系在这里通过实例车厂::
如果要发送GET请求,则可以略微修改代码以适合您的需求。具体来说,您必须在URL的构造函数中添加参数。然后,也将其注释掉
wr.write(data);
没有写的一件事是您应该注意的,它是超时。特别是如果要在WebServices中使用它,则必须设置超时,否则上面的代码将无限期地等待,或者至少等待很长时间,这大概是您不想要的。
这样设置超时时间
conn.setReadTimeout(2000);
,输入参数以毫秒为单位