자바에서 HTTP 요청을 보내는 방법은 무엇인가요?

Java에서 HTTP 요청 메시지를 작성하여 HTTP 웹서버로 전송하는 방법은 무엇인가요?

질문에 대한 의견 (3)
해결책

java.net.HttpUrlConnection]1을 사용할 수 있습니다.

예제 (여기에서), 개선 사항 포함. 링크 부패의 경우 포함됩니다:

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)

오라클 자바 튜토리얼]1 참조

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();
    }
}
해설 (11)

다른 사람들이 아파치 클라이언트를 추천하는 것을 알고 있지만, 이는 거의 보장되지 않는 복잡성(즉, 잘못될 수 있는 더 많은 것들)을 추가합니다. 간단한 작업의 경우 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();
}
해설 (2)

아파치 하테프콤프로넨츠. 그 두 개의 모듈 - 하테프코리하테프클리나 바로 이용할 수 있습니다.

나쁜 것이 아니라 선택, 하테프콤프로넨츠 불지옥으 스테퍼리코네크션 는 추상적 많은 비효율적임 코딩 하였다. 난 진짜 원한다면 이, HTTP 서버 / 클라이언트 추천합니까 많이 지원할 수 있는 최소한의 코드입니다. 그나저나, 하테프코리 애플리케이션과도 최소한의 기능을 사용할 수 있다 (클라이언트나 서버를) 에 대한 지원을 필요로 하는 반면, 여러 인증 구성표과 클라이언트뿐 하테프클리나 사용할 것인지, 쿠키를 상술합니다.

해설 (2)

39 의 here& 전체 jave 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());
    }
  }
}

새로운 자원을 사용하여 시도하시겠습니까 자동 닫으십시오 자동 닫으십시오 린퍼타슬림 스캐너, 이 되는 것이다.

해설 (2)

이 도움이 될 것이다. # 39, JAR 를 추가할 수 있는 't forget don& 하테프클리앵 t.자' 을 classpath.

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();
        }
    }
}
해설 (2)

Java http client 구글 API 는 http 요청을 위해 좋은. 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();
    }
}
해설 (4)

이 같은 소켓을 사용할 수 있습니다.

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();    
해설 (3)

39 에 대한 링크를 보내는 there& 숭배자들로부터도 게시물로의 요청 [여기서요] [1] 디포트 by example:

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

Get 요청을 전송할지 스케쳐내 요구에 맞게 약간 코드를 수정할 수 있습니다. 특히 내부에 URL 의 구성자를 매개 변수를 추가할 수 있습니다. 그런 다음, 이 또한 설명줄로 라스라이트 (데이터) ','

한 가지는, s not 기록되었으므로 that& # 39 는 시간초과와 하고 바랄 합니다. 특히 이를 사용하려면 웹 서비스, 그렇지 않으면 설정할 수 있습니다 시간초과와 위의 코드는 무기한 기다리는 충족하거나 매우 긴 시간 동안 적어도 및 it& # 39, s, t want don& # 39 뭔가 있을 수 있습니다.

이렇게 콘스스트레더타임우스 timeouts 설정된 ' (2000년),' 의 입력 파라메트가 밀리초입니다

[1]: //www.exampledepot.com/egs/java.net/post.html http://web.archive.org/web/20120101100355/http

해설 (0)