Jak wysłać żądanie HTTP w Javie? [duplikat]

To pytanie ma już odpowiedź tutaj:

W Javie, jak skomponować wiadomość żądania HTTP i wysłać ją do serwera HTTP?

Author: Yatendra Goel, 2009-09-01

9 answers

Możesz użyć java.net. HttpUrlConnection.

Przykład ( stąd ), z ulepszeniami. Włączone w przypadku zgnilizny ogniwa:

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();
    }
  }
}
 270
Author: duffymo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-20 16:34:44

From Oracle ' s java tutorial

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();
    }
}
 210
Author: Chi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-25 16:20:03

Wiem, że inni polecą klienta http Apache, ale to dodaje złożoności (tj. więcej rzeczy, które mogą pójść źle), która rzadko jest uzasadniona. Dla prostego zadania, java.net.URL zrobi.

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();
}
 63
Author: erickson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-31 22:38:53

Apache HttpComponents . Przykłady dwóch modułów - HttpCorei HttpClient pozwolą Ci zacząć od razu.

Nie to, że HttpUrlConnection jest złym wyborem, HttpComponents usunie wiele żmudnego kodowania. Polecam to, jeśli naprawdę chcesz obsługiwać wiele serwerów/klientów HTTP z minimalnym kodem. Nawiasem mówiąc, HttpCore może być używany dla aplikacji (klientów lub serwerów) o minimalnej funkcjonalności, podczas gdy HttpClient jest do być używane dla klientów, którzy wymagają wsparcia dla wielu schematów uwierzytelniania, obsługi plików cookie itp.

 54
Author: Vineet Reynolds,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-11 18:12:17

Oto kompletny program 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());
    }
  }
}

Nowa funkcja try-with-resources automatycznie zamknie skaner, który automatycznie zamknie strumień wejściowy.

 23
Author: Janus Troelsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-14 14:57:32

Google java http client posiada ładne API dla żądań http. Możesz łatwo dodać obsługę JSON itp. Chociaż dla prostego żądania może to być przesada.

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();
    }
}
 13
Author: Tombart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-10 15:56:33

To ci pomoże. Nie zapomnij dodać JAR HttpClient.jar do ścieżki klasowej.

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 protected]");

        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();
        }
    }
}
 12
Author: Satish Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-20 19:16:22

Możesz użyć Socket do tego typu

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();    
 9
Author: laksys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-18 14:02:06

Jest świetny link o wysłaniu zapytania POST tutaj przez przykład:

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) {
}

Jeśli chcesz wysłać żądanie GET, możesz zmodyfikować kod nieznacznie, aby odpowiadał Twoim potrzebom. W szczególności musisz dodać parametry wewnątrz konstruktora adresu URL. Następnie skomentuj to wr.write(data);

Jedna rzecz, która nie jest napisana i należy się wystrzegać, jest timeouts. Szczególnie jeśli chcesz go używać w WebServices musisz ustawić timeouty, w przeciwnym razie powyższy kod będzie poczekaj w nieskończoność lub przynajmniej bardzo długo, a to jest coś, czego prawdopodobnie nie chcesz.

Timeouty są ustawiane tak conn.setReadTimeout(2000); parametr wejściowy jest w milisekundach

 7
Author: tzik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-20 11:40:52