Hello everyone, I am trying to connect to the html server, send a request there and each server returns an HTTP / 1.0 400 Bad Request error to me.

Here is the code

import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class start { @SuppressWarnings({ "resource" }) public static void main(String[] args) throws UnknownHostException, IOException { String host = "google.com"; Socket connection = new Socket (host,80); OutputStream sout; sout = connection.getOutputStream(); DataOutputStream out = new DataOutputStream(sout); String line = "GET / HTTP/1.1" +"\nHost: google.com" +"\nConnection: ke123ep-alive" +"\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" +"\nUpgrade-Insecure-Requests: 1" +"\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36" +"\nAccept-Encoding: gzip, deflate, sdch" +"\nAccept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4"; out.writeUTF(line); System.out.println("запрос отправлен"); InputStream in = connection . getInputStream (); System.out.println("ответ с сервера принят"); int i=-1; while((i=in.read())!=-1){ System.out.print((char)i); } } } 
  • It seems that the problem in writeUTF: HTTP 1.1 is not transmitted to UTF. - Andrewus

2 answers 2

DataOutputStream.writeUTF(String str) transfers the contents of the string in its own special format . To send http headers, just pass the string in ASCII:

 sout.write( line.getBytes( StandardCharsets.US_ASCII ) ); 

Note that the header set must end with an empty string.

  • Thanks for the quick reply, but now I don’t receive a response from the server - as1andrey1
  • +"\n\n"; Add to your title bar. - zRrr
  • everything works, thanks very much) - as1andrey1

Try to use better for such purposes, ready-made tools for implementing Http client.