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.
Related
I am trying to send a gzip encoded data using post but getting a 400 response every time
I tried the following code
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Authorization", parameters[1]);
conn.setRequestProperty("Content-Encoding", "gzip");
ByteArrayOutputStream baos = new ByteArrayOutputStream(messageBody.length());
GZIPOutputStream gzip = new GZIPOutputStream(baos);
gzip.write(messageBody.getBytes(Charset.forName("UTF-8")));
OutputStream os = conn.getOutputStream();
os.write(baos.toByteArray());
os.close();
gzip.close();
conn.connect();
int res = conn.getResponseCode();
The response code is always 400. Kindly help.
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.
I have the following code
URL url = new URL(pushURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/restService");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
if(conn.getResponseCode() == 200){
logger.debug("Success");
} else {
logger.debug("Time out set for 30 seconds");
}
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();
If I am not interested in the response from the server, can I remove the following code?
if(conn.getResponseCode() == 200){
logger.debug("Success");
} else {
logger.debug("Time out set for 30 seconds");
}
Considering that the code, in it's entirety as it is, causes a java.net.ProtocolException, is there a way to still grab the server response and execute conn.getOutputStream();? In what order? What are the consequences of not obtaining the response aside from the obvious reporting concerns?
The problem is that once you get the response code, you have sent your post. In your code, you don't write anything to the output stream before you get the response. So, you are essentially sending nothing over the post (just that header info), getting the response code, and then trying to write to it again, which is not allowed. What you need to do is write to the output stream first, and then get the response code like so:
public static void main(String[] args) throws IOException {
URL url = new URL(pushURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/restService");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();
for (char c : input.toCharArray()) {
os.write(c);
}
os.close();
if(conn.getResponseCode() == 200){
System.out.println("Success");
} else {
System.out.println("Time out set for 30 seconds");
}
}
Here's a little tutorial:
Reading and Writing Tutorial
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)"
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.