Reputation: 2784
I'm trying make HTTP Post request with Java, here the code
protected class DownloadInfoOfWeather extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
String result = "";
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("User-Agent", USER_AGENT);
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.setDoOutput(true);
DataOutputStream write = new DataOutputStream(connection.getOutputStream());
write.writeBytes(params[1]);
write.flush();
write.close();
// Response: 400
Log.e("Response", connection.getResponseCode() + "");
} catch (Exception e) {
Log.e(e.toString(), "Something with request");
}
return null;
}
}
public void clickHelloWorld (View view) {
DownloadInfoOfWeather downloadInfoOfWeather = new DownloadInfoOfWeather();
String url = "https://query.yahooapis.com/v1/public/yql";
String body = "q=\"select wind from weather.forecast where woeid=2460286\"&format=json";
downloadInfoOfWeather.execute(url, body);
}
when I run this code, I get Response: 400;
I use Yahoo API
In other hand with curl everything works fine
Does anyone know how fix this issue?
Upvotes: 0
Views: 6630
Reputation: 161
If you remove quotes from your string it will work just fine - like that
.execute(
"https://query.yahooapis.com/v1/public/yql",
"q=select wind from weather.forecast where woeid=2460286&format=json")
Also I cleaned up your connection code a little
protected static class DownloadInfoOfWeather extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "*/*");
connection.setDoOutput(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(params[1]);
writer.close();
connection.connect();
// Response: 400
Log.e("Response", connection.getResponseMessage() + "");
} catch (Exception e) {
Log.e(e.toString(), "Something with request");
}
return null;
}
}
Upvotes: 4
Reputation: 291
it means 1- the web service has problem
2-you send a wrong parameter(your method is post)
and if you want get Strings beter do this :
protected class DownloadInfoOfWeather extends AsyncTask<void//notice, Void, String>
make a counstructor :
DownloadInfoOfWeather(Strings 1 , Strings 2){
}
then :
new Asyntask(Strings).execute();
//+ this
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
Upvotes: 0