I am trying to post a JSON message to a site and to retrieve a JSON message back.
java.net.ProtocolException: method does not support a request body: POST
Does anyone know what is wrong? Thanks in advance
HttpURLConnection conn=null;
try{
URL url=new URL(urlString);
String userPassword = userName +":" + passWord;
byte[] bytes=Base64.encode(userPassword.getBytes(),Base64.DEFAULT);
String stringEncoding = new String(bytes, "UTF-8");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "Basic " + stringEncoding);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
Log.i("Net", "length="+conn.getContentLength());
Log.i("Net", "contentType="+conn.getContentType());
Log.i("Net", "content="+conn.getContent());
conn.connect();
}catch(Exception e){
Log.d("Url Formation Connection", e.toString());
}
//output{
try{
String requestString="{“ ";
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(requestString.toString());
wr.flush();
//input{
BufferedReader rd = null;
String response=" ";
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer responseBuff = new StringBuffer();
while ((line = rd.readLine()) != null) {
// Process line...
responseBuff.append(line);
}
response = responseBuff.toString();
Log.d("response", response);
}catch(Exception e){
Log.d("buffer error", e.toString());
}finally {
if (is != null) {
try {
wr.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It could be that the server you're connecting to doesn't allow POST operations. I would try a GET request first, to see if you have permissions for that web service method.
Also, you could try your luck with a simpler HttpClient, although I haven't tested this solution myself: http://www.geekmind.net/2009/11/android-simple-httpclient-to.html
Just a guess but can you try setting:
conn.setDoOutput(false);
The documentation says: "Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body." HttpURLConnection
Since you do not have anything in your body, might as well set it to false.
The documentation Android has for setRequestMethod is minimal, however your error states that POST is not a valid method. Try using PUT instead:
conn.setRequestMethod("PUT");
Also see this post for any tweaks you may need to make.
Related
I have been running into a very strange problem. I am trying to implement log in service in my app. When I pass right email and password service returns response as expected(means no error comes) but when I delibrately pass wrong email or password geInputStream() method throws FileNotFoundException. I don't know what is the reason behind this.Further more, before calling getInputStream() method i checked status code as well(this is the case when I am passing wrong email and password intentionally).The status code was 500. I checked for 500 and that was internal server error. My question is why is that so? I mean when intentionally passing wrong email or password why internal server occurred? One more thing I would like to mention that I have checked the same service on post man it is working fine as expected. If i pass wrong email or password postman returns the expected error. Below is the code I am using
private String invokeWebservice() {
String data = null;
HttpURLConnection conn = null;
BufferedReader in = null;
try {
String webservice = Constants.BASE_URL + serviceName;
LogUtility.debugLog("webservice just called "+ webservice);
URL url = new URL(webservice);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setUseCaches(false);
if (isPost) {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
if (jsonObject != null)
writer.write(jsonObject.toString());
writer.close();
}
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null)
sb.append(l + nl);
in.close();
data = sb.toString();
return data;
} catch (Exception e) {
LogUtility.errorLog("exception while calling web service");
} finally {
try {
if (conn != null)
conn.disconnect();
if (in != null)
in.close();
} catch (Exception ex) {
// LogUtility.errorLogWithException(ex, ex.getMessage());
}
}
return data;
}
Any help?
After spending some time now I was able to solve my problem.Posting my answer for others. Passing wrong email and password to the service was right and server was consuming those parameters as well and because there was an error(because email and password) that is why it was returning 500 code. So, I checked for status code if it was 200 then I used getInputStream() method and else i called getErrorStream() method. By this way i got the stream that has property for error(this property contains error detail). Below is the code i used
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
Hope it helps other as well.
My project is targeted to SDK 23, and from now on, as far as I know, I have to use HttpURLConnection instead of HttpClient to make post requests, but I keep getting 501 response code from my webservice (I'm pretty sure it's fully functional, I have no doubt) when making post requests to store users in a remote mysql database. Here follows the main connection code:
class DatabaseConnector extends AsyncTask<String, Void, String> {
private final String CONNECTION_URL = "webservice_address";
#Override
protected String doInBackground(String... params) {
String response = "initial value";
try {
URL url = new URL(CONNECTION_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
JSONObject json = new JSONObject();
json.put("query", params[0]);
JSONObject conn = new JSONObject();
conn.put("database", "database");
conn.put("hostname", "hostname");
conn.put("password", "password");
conn.put("username", "username");
conn.put("port", "port");
json.put("conn", conn.toString());
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(json.toString());
wr.flush();
wr.close();
con.connect();
//display what returns the POST request
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
System.out.println("Response CODE: "+ con.getResponseCode());
if (HttpResult == HttpURLConnection.HTTP_OK) {
System.out.println("Passed1");
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
while ((response = br.readLine()) != null) {
sb.append(response + "\n");
}
br.close();
System.out.println("E: " + sb.toString());
response = sb.toString();
} else {
System.out.println("E2: "+con.getResponseMessage());
response = "Error1: "+con.getResponseMessage();
}
} catch (Exception e) {
response = "Error2: "+e.toString();
}
return response;
}
}
And in my fragment I make the network calls:
try {
String result = new DatabaseConnector().execute("SELECssT 1").get();
Toast.makeText(ContentActivity.this, "Result: "+result, Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(ContentActivity.this, "Error3: "+ex.toString(), Toast.LENGTH_LONG).show();
}
Nevermind that wrong sql statement, it's meant to be like that, I want the webservice to echo back that syntax error. I have tried many stuff, codes, examples, but it doesn't seem to work.
The point is: I keep getting error code 501 Not Implemented. Why? And how can I fix that?
EDIT:
Any tips or comments on how to improve the way I make network calls on android is welcome, I'm pretty new to that. I'm using a Async call but somehow it's still executing in the main thread, cause the debugger complains:
09-25 19:17:32.714 28853-28853/br.com.developer.package I/Choreographer﹕ Skipped 80 frames! The application may be doing too much work on its main thread.
Thank you all.
Today I'm making my first attempt of sending a POST request with a JSON to save some data, and I'm not being able to do so.
My app works by signing in, and then save, modify and delete data. It's already done in iOS, but since I'm new to Android, I'm not sure how to do it.
Here's my POST function:
public String POST(String targetURL, String urlParameters, String user, String pwd) {
URL url;
String u = targetURL;
HttpURLConnection connection = null;
try {
// Create connection
// u=URLEncoder.encode(u, "UTF-8");
url = new URL(u);
connection = (HttpURLConnection) url.openConnection();
// cambiarlo luego al usuario q esta logeado
String login = user + ":" + pwd;
String encoding = new String(org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(login)));
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("Content-Type", "plain/text");// hace q sirva con el string de json
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(120000);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
this.setResponseCode(connection.getResponseCode());
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();
}
}
}
The method above is executed with Asynctask, and even if I use it to Login using Spring security, it works, and even I can save for internal usage the username, password, and secret token.
I dunno if I need to put the token in a header or something, because I already did that, with no positive results.
I'm supposing that the only permission I need to execute this is the internet one, so in my manifest file I specified that permission.
I'm going crazy with this issue, please help!
Thanks in advance.
EDIT:
Sorry guys, I'm kinda new to this way of asking, and also, not an English native speaker :P
The output I receive after sending the request, is the HTML of the page that handles logging in into the web app... I need like a json response or something like that to make sure the request was saved correctly
Try handling your cookies
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
This should be a singleton.
I'm trying to do a post method for a REST service, but I'm not getting any response from server:
public JSONObject postValues (String strUrl, String strJsonArray) throws Exception{
JSONObject jsonObject = null;
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
strJsonArray = "data=" + strJsonArray;
Log.e("result",""+strJsonArray);
OutputStream os = conn.getOutputStream();
os.write(strJsonArray.getBytes());
os.flush();
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
Log.e("output",output);
sb.append(output);
}
Log.e("output",sb.toString());
jsonObject = new JSONObject(sb.toString());
conn.disconnect();
return jsonObject;
}
When I see my logCat a get:
output {}
I know that the server is working right because I'm using the "advanced REST client" plugin of google chrome. If I call the URL manually (using the plugin of course)I get the desired answer:
{"message":"OK","code":200}
But if I try to use my function, my strJsonArray is inserted but I get an empty respond from server.
Is there anything wrong with my code?.
Everything looks good...
You could use Wireshark to capture the packets sent to and received from the server using an emulator and the chrome rest client. Then you can compare them and maybe find out what's wrong.
You could also check if theres something in the error stream (conn.getErrorStream()).
Im currently working on an Android app with heavy server side communication. Yesterday I got a bug report saying that the users aren't able to send (simple) special characters such as ëäï.
I searched but didn't find anything helpful
Possible duplicate ( without answer ):
https://stackoverflow.com/questions/12388974/android-httpurlconnection-post-special-charactes-to-rest-clint-in-android
My relevant code:
public void execute(String method) {
HttpsURLConnection urlConnection = null;
try {
URL url = new URL(this.url);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setReadTimeout(30 * 1000);
urlConnection.setDoInput(true);
if (secure)
urlConnection.setRequestProperty("Authorization", "Basic " + getCredentials());
if (body != null) {
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setFixedLengthStreamingMode(body.length());
urlConnection.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(body);
dos.flush();
dos.close();
}
responseCode = urlConnection.getResponseCode();
message = urlConnection.getResponseMessage();
InputStream in = null;
try {
in = new BufferedInputStream(urlConnection.getInputStream(), 2048);
} catch (Exception e) {
in = new BufferedInputStream(urlConnection.getErrorStream(), 2048);
}
if (in != null)
response = convertStreamToString(in);
} catch (UnknownHostException no_con) {
responseCode = 101;
}catch (ConnectException no_con_2){
responseCode = 101;
}catch(IOException io_ex){
if(io_ex.getMessage().contains("No authentication challenges found")){
responseCode = 401;
}else
responseCode = 101;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
body is a String ;-)
Hope we can solve this together
UPDATE:
Tried:
writeUTF()
need a server capable of understanding the modified UTF-8
byte[] buf = body.getBytes("UTF-8");
dos.write(buf, 0, buf.length);
strings work but no special chars
update: Got it working with StringEntity(* string, "UTF-8") then parse the result to a byte[] and write it with dos.write(byte[])!
--
Setting the encoding of the StringEntity did the trick for me:
StringEntity entity = new StringEntity(body, "UTF-8");
seen here: https://stackoverflow.com/a/5819465/570168
i am not totally sure buy try this utility for your case
URLEncoder.encode(string, "UTF-8")
I faced this problem in android while passing a json with special char (ñ).
In my WebApi method, [FromBody] param is giving null, it seems it can't parse the json.
I got it working by getting bytes as UTF-8 then writing it in DataOutputStream (Client-side fix).
byte[] b = jsonString.getBytes("UTF-8");
os.write(b, 0, b.length);