getting HTTP/1.1 400 Bad Request - java

This is my code. I am receiving HTTP/1.1 400 Bad Request. Not sure if I did something wrong here.
try {
//client = new DefaultHttpClient();
client=HttpClientBuilder.create().build();
get = new HttpGet(queryURL.toString());
HttpResponse response = client.execute(get);
if(HttpStatus.SC_OK!=response.getStatusLine().getStatusCode()) {
throw new ServiceException(this, response.getStatusLine().getStatusCode()+"", response.getStatusLine().toString());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuffer json = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
json.append(line);
}
The error message.
ServiceException: HTTP/1.1 400 Bad Request

To find out reason of the Bad Request firstly you should see the response text. You can write as following:
client=HttpClientBuilder.create().build();
get = new HttpGet(queryURL.toString());
HttpResponse response = client.execute(get);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder responseAsString = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
responseAsString.append(line);
}
if(HttpStatus.SC_OK!=response.getStatusLine().getStatusCode()) {
throw new ServiceException(this, response.getStatusLine().getStatusCode()+"", response.getStatusLine().toString() + ", cause: " + responseAsString);
}

Related

Error message in Http request

I am using the code below to make http request but when exception is thrown I am not able to fetch error message per field. In postman it does show proper error message:
HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
con.setSSLSocketFactory(sc.getSocketFactory());
con.setDoOutput(true);
con.setRequestProperty("Authorization","Basic KEY")
con.setRequestProperty("Content-Length", Integer.toString(data.length()));
try {
con.getOutputStream().write(data.getBytes("UTF-8"));
final BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
stringBuffer = new StringBuffer();
while ((line = rd.readLine()) != null) {
stringBuffer.append(line);
}
rd.close();
}catch(Exception e){
println stringBuffer.toString()
throw new Exception("Some error occurred " + e.message)
}
It simply shows the message "Server returned HTTP response code: 422 for URL: https://test.api.promisepay.com/users/35"
Whereas in Postman it shows:
{
"errors": {
"mobile": [
"already exists"
]
}
}
You can't read error using input stream instead you should use error stream for that purpose.
Below is an example snippet :
After writing data to output stream you should check what response code has been returned :
int respCode = con.getResponseCode();
Then check whether response code returned is 200 or not, if it is not then there has been some error :
InputStream is=null;
if(respCode==200){
is = con.getInputStream();
} else if (urlConnection.getErrorStream() != null) {
is = con.getErrorStream();
}
Now you can change your code for reading the error :
final BufferedReader rd = new BufferedReader(new
InputStreamReader(is));
stringBuffer = new StringBuffer();
while ((line = rd.readLine()) != null) {
stringBuffer.append(line);
}
rd.close();
Hope this may help!

Different content with Apache's DefaultHttpClient and HttpURLConnection

I want to read the content of a website (http://www.google.com) in an Android app. Using the deprecated DefaultHttpClient still works fine and I always get a content length of about 15.000 characters:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet g = new HttpGet(target);
HttpResponse res = client.execute(g);
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);
However, when I use a HttpURLConnection to achieve the same, I get a different content with a length of about 100.000 characters.
HttpURLConnection connection = (HttpURLConnection) new URL(target).openConnection();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);
Does anybody know, why there is such a big difference. Thanks!
The problem is caused by the user agent. With the following code, the two requests behave the same:
connection.setRequestProperty("User-Agent","Apache-HttpClient");

Print Wit.ai response in console [java]

hi all I'm trying to send a request to Wit to a simple wit application that i've created and I'm doing this in java. I'm trying to print the wit response into the console but the only thing that prints is the following line:
class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
The code that I am using to send the request is a code that I have found on this forum, I repost it for be more specific:
public static String getCommand(String command) throws Exception {
String url = "https://api.wit.ai/message";
String key = "MY_SERVER_KEY";
String param1 = "my_param";
String param2 = command;
String charset = "UTF-8";
String query = String.format("v=%s&q=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty ("Authorization", "Bearer " + key);
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
return response.toString();
}
how can i return the wit response?
EDIT:
I'm trying with apache as you suggested to me, but it keeps to send me error 400.
Here the code:
public static void getCommand2(String command) throws Exception {
String query = URLEncoder.encode(command, "UTF-8");
String key = "my_key";
String url = "https://api.wit.ai/message?v="+my_code+"q"+query;
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("Authorization: Bearer", key);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
}
You don't have to use Apache
Taken from the Wit.ai android-sdk.
public static String convertStreamToString(InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
is.close();
return sb.toString();
}
The problem you were having is that the InputStream's toString method is only returning it's class name. Another thing you can try is using HTTPURLConnection rather than just the simple URLConnection, since you know it will be an HTTP request as opposed to another protocol.

How do I read a HTTP response if the server returned a 502 error?

I used URLConnection to send a POST request to a server and I am using the following code to read the response:
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
response += line;
}
reader.close();
However, the server will sometimes return a 502 error with a meaningful error message in the response, which I would like to obtain. My problem is that attempting to create the BufferedReader in that case will result in a java.io.IOException:
Server returned HTTP response code: 502 for URL: <url>
How can I bypass this?
Modify your code along these lines so that you can get the errorstream rather than throw the IOException
HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
response += line;
}
reader.close();

Get web content

I'm trying to get XML content from an URL:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://www.domain.com/test.aspx"));
HttpResponse response = client.execute(request);
in = response.getEntity().getContent();
When I write out the response content, this is truncated before the end of the content.
Any idea?
Did you use a InputStreamReader for the input stream in?
String s = "";
String line = "";
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
try {
while ((line = rd.readLine()) != null) { s += line; }
} catch (IOException e) {
// Handle error
}
// s should be the complete string
maybe i have solved, was the android emulator. Simply restarting it all works fine.
Thanks to all

Categories

Resources