I am sending GET method to server but receiving POST method - java

I am sending GET command to the server but in the Apache log I am getting POST method.
URL url = new URL("http://192.168.0.111/shakil/shakil.php/?data=shakil,123,123,123");
JSONObject postDataParams = new JSONObject();
postDataParams.put("name", "nazmul");
postDataParams.put("email", "hossainnazmul93#gmail.com");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000 /* milliseconds */);
conn.setConnectTimeout(3000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
Although the method is GET. Can Any one suggest me what is the problem?

Comment this line:
conn.setDoOutput(true);

I am sending GET method
No you aren't. This line:
conn.setDoOutput(true);
sets the request method to POST. You are also doing some output, which doesn't match with a GET request either. If you want a GET, remove the line above and the lines that do the output. Probably you should send the parameters encoded into the URL.

Related

How to get response from HttpURLConnection POST

I am trying to send a POST (with XML in the body) to an API and get a response back that is XML. There are confirmation or error details that I need to get from the response body (from within the ERRORelement).
I can send the POST and it does trigger the change in the API, but I cannot read the response.
When I send the POST manually from Postman, I trigger the change in the API and I can see the response from the API as text/html;charset=charset=utf-8
Here is my current code:
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xmlString);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
The response body should be in the following format:
<Root>
<Session>
<UserId>theUserID</UserId>
<Password>thePassword</Password>
<ERROR Status="0" Description="Logon Successful" />
</Session>
<ActivityList>
<Activity Type="ReqUp" Incident="12345" ElapsedTime="350"
Description="example response"
Status="Complete">
<ERROR Status="0" Description="OK" />
</Activity>
</ActivityList>
</Root>
Current/Actual result:
line is showing as null
Since you want xml to come back from the server, it is likely that you need to add an "accept" header to the request to tell the server that you (the client) will "accept" xml. From your post, it appears that the default is html.
This might work for you:
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("accept", "application/xml");
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
If you are sending xml to the server, you also may want to add a "content-type" header, like this:
conn.setRequestProperty("content-type", "application/xml");
ref: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
There was a bug in my original code that prevented line from ever forming anything other than null.
the correct code is as follows:
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("accept", "text/html");
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xmlString);
writer.flush();
String builtResponse = "";
String line ="";
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
builtResponse += line;
}
writer.close();
reader.close();

HttpURLConnection post method issue

I have a problem on HttpURLConnection in post method. Everything is working fine on get method however, when I try to use Post method. I'm getting this error message.
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL
Here's my code snippet. I hope you could help me about this.
URL url = new URL(my url/userInfo);
String encoding = Base64.getEncoder().encodeToString(("username:password").getBytes("UTF-8"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("x-csrf-token", "fetch");
String csrfToken = connection.getHeaderField("x-csrf-token");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
String output = in.readLine();
in.close();
String content = data // expected data to retrieve
URL url2 = new URL(my URL);//another url to push the data retrieve
HttpURLConnection connection2 = (HttpsURLConnection) url2.openConnection();
connection2.setDoInput(true);
connection2.setDoOutput(true);
connection2.setRequestMethod("POST");
connection2.setRequestProperty("Authorization", "Basic " + encoding);
connection2.setRequestProperty("Accept", "application/json");
connection2.setRequestProperty("x-CSRFToken", csrfToken);
connection2.setRequestProperty("cache-control", "no-cache");
OutputStream os = connection2.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(data);//this is where the data will be pushed
osw.flush();
osw.close();
os.close();
the idea is, we need first to get the x-csrf-token and data from the first link, which is okay. After GET Method execution, the POST method will occur. unfortunately, the post method is not working. I'm getting the error message shown above. By the way, we tried to do a post method in POSTMAN and it' working fine.
Hoping you could help me about this.

Post BASE64 to server

I am trying to send one image with BASE64 to server and always got 408 with this message "The request body did not contain the specified number of bytes. Got 13.140, expected 88.461". How can I solve that?
I tried to use Retrofit, HttpURLConnection and got the same error. I think that is some parameter on app.
Gson gson = new Gson();
String jsonParam = gson.toJson(enviarPlataforma);
URL url = new URL("");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setFixedLengthStreamingMode(jsonParam.getBytes().length);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam);
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
The UTF-8 bytes must be taken, and send as-is. The DataOutputStream is for something else entirely. As it is one write, you can simply use the OutputStream you get from the connection. A BufferedOutputStream probably serves no purpose.
Flushing before a close is never needed. One needs to flush on a standing, continuing line only.
Try-with-resources closes automatically, also when some exception was thrown.
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
//conn.setDoInput(true);
byte[] content = jsonParam.getBytes("UTF-8"):
conn.setFixedLengthStreamingMode(content.length);
Log.i("JSON", jsonParam.toString());
try (OutputStream os = conn.getOutputStream()) {
os.write(content);
}
I solve my problem. I don't know why but when I'm using Fiddler I got this message.
Thank you guys.

getErrorStream: stream closed, getInputStream: works

I have a weird issue with my code:
URL url = new URL(searchUrlPOST.replace("%accessToken", accessToken));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
That works perfectly fine as long as the server is responding with a proper status code. If he however responds with something like a 400 and i replace the conn.getInputStream() with a conn.getErrorStream() I get a
Exception in thread "main" java.io.IOException: Stream closed
How come?
I'm not sure but:
Please make sure that
searchUrlPOST.replace("%accessToken", accessToken)
returns a valid url, this error can been thrown by using an invalid url at "new Url(String url)"

Android Post UTF-8 HttpURLConnection

I am currently developing an application that needs to interact with the server but i'm having a problem with receiving the data via POST. I'm using Django and then what i'm receiving from the simple view is:
<QueryDict: {u'c\r\nlogin': [u'woo']}>
It should be {'login': 'woooow'}.
The view is just:
def getDataByPost(request):
print '\n\n\n'
print request.POST
return HttpResponse('')
and what i did at the src file on sdk:
URL url = new URL("http://192.168.0.148:8000/data_by_post");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
String parametros = "login=woooow";
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("charset","utf-8");
urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(parametros.getBytes().length));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(parametros);
writer.close();
os.close();
I changed the Content-Length to see if that was a problem and then the problem concerning thw value of login was fixed but it was by hard coding (which is not cool).
ps.: everything except the QueryDict is working well.
What could i do to solve this? Am i encoding something wrong at my java code?
thanks!
Just got my problem solved with a few modifications concearning the parameters and also changed some other things.
Having parameters set as:
String parameters = "parameter1=" + URLEncoder.encode("SOMETHING","UTF-8");
then, under an AsyncTask:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
//not using the .setRequestProperty to the length, but this, solves the problem that i've mentioned
conn.setFixedLengthStreamingMode(params.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(params);
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
Then, with this, i got the result from django server:
<QueryDict: {u'parameter1': [u'SOMETHING']}>
which is what i was wanting.

Categories

Resources