2014-01-20 6 views
0

Я написал код для моего приложения swing для входа в систему, я должен получить флаг в качестве ответа от веб-службы как формат json, проблема, с которой я сталкиваюсь, заключается в том, что когда я отправляю данные, m получить плохой запрос 400, если я устанавливаю определенные заголовки или 500 внутренних ошибок сервера, если заголовки не установлены.Ошибка с неправильным запросом

соединение Класс

public class Connection extends Thread { 

private String url1; 
private JSONObject data; 
String line; 
//Constuctor to initialize the variables. 

public Connection(String url1, JSONObject data) { 
    this.url1 = url1; 
    this.data = data; 
    start(); 
} 

public void run() { 
    ConnectionReaderWriter(); 
} 

//To fetch the data from the input stream 
public String getResult() { 
    return line; 
} 

public String ConnectionReaderWriter() { 
    URL url; 
    HttpURLConnection connection = null; 
    ObjectOutputStream out; 
    try { 
     /*URL url = new URL(Url.server_url + url1);  //Creating the URL.  
     URLConnection conn = url.openConnection(); //Opening the connection. 
     conn.setDoOutput(true); 
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     wr.write(data); //Posting the data to the ouput stream. 
     wr.flush(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     line=rd.readLine();  //Reading the data from the input stream.  
     wr.close(); 
     rd.close();*/    
     url = new URL(Url.server_url + url1);  //Creating the URL. 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("POST"); 
     // Headers 
     connection.setRequestProperty("Content-Type", "application/json"); 
     connection.setRequestProperty("Accept", "application/json"); 
     // API key has to be passed 
     connection.setRequestProperty("api_key", "123456"); 
     connection.setUseCaches(false); 
     //System.out.println(connection.getRequestProperty("api_key"));    
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     //Send request 
     out = new ObjectOutputStream(connection.getOutputStream()); 
     out.write(data.toString().getBytes()); 
     out.flush(); 
     System.out.println(data.toString()); 
     int rescode = connection.getResponseCode(); 
     line = connection.getResponseMessage(); 
     System.out.println(line +" : "+ rescode); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));    
     line = rd.readLine();  //Reading the data from the input stream.  
     rd.close(); 
     out.close();    
     System.out.println("fsgjv: "); 

    } catch (MalformedURLException ex) { 
     Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex); 
     String nonet = "No Network Connection"; 
     line = nonet; 
    } catch (IOException ex) { 
     Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex); 
     String nonet = "No Server Connection"; 
     line = nonet; 
    } 
    return line; //Return te stream recived from the input stream. 
} 
} 

ошибка, выдаваемым приводятся ниже.

{"username":"[email protected]","password":"123"} 
Bad Request : 400 
Jan 20, 2014 6:00:04 PM SupportingClass.Connection ConnectionReaderWriter 
SEVERE: null 
java.io.IOException: Server returned HTTP response code: 400 for URL:  http://192.168.10.241/MobpazAdmin/web/app_dev.php/ws/terminalusers/terminaluserlogins.json 
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) 
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:525) 
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674) 
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1672) 
at java.security.AccessController.doPrivileged(Native Method) 
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1670) 
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1243) 
at SupportingClass.Connection.ConnectionReaderWriter(Connection.java:81) 
at SupportingClass.Connection.run(Connection.java:40) 
    Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: http://192.168.10.241/MobpazAdmin/web/app_dev.php/ws/terminalusers/terminaluserlogins.json 
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625) 
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468) 
at SupportingClass.Connection.ConnectionReaderWriter(Connection.java:78) 
... 1 more 

Скажите, пожалуйста, если я допустил ошибку в коде, я проверил код на стороне сервера, он работает правильно. данные, которые должны быть переданы в JSON объект приведен ниже

{"username":"[email protected]","password":"123"} 

ответ

0

Я меняю этот метод доступа сейчас, я использую Httpget для достижения того же. Вам необходимо загрузить соответствующий файл httpcomponents-client jar и добавить его в библиотеку. Используемый код приведен ниже.

data = URLEncoder.encode("searchvariable", "UTF-8") + "=" + URLEncoder.encode("name", "UTF-8"); 
HttpGet g = new HttpGet(Url.server_url + url1+"?"+data); 

Данные - это параметры, которые необходимо передать вместе с URL. Проблема возникла из-за неправильного метода доступа.

0

Проблема, приходит с сервера, так как он возвращает код состояния 400. Вы можете проверить журналы сервера, чтобы найти больше информации?

Смежные вопросы