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)"
Related
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.
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.
i want get json from this url
but get error like this :
java.io.IOException: Server returned HTTP response code: 403 for URL: http://test.dotconnect.io/data_api/reports/1bf4bc70b31d4d92b50a6d965c52fcec
this is my complete code :
InputStream is = null;
JsonReader rdr = null;
OutputStreamWriter out = null;
String path = "http://test.dotconnect.io/data_api/reports/";
int timeout = 6000000;
String key ="Authorization : 402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
URL url = new URL(path+request.getParameter("reportTaskToken"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setDoInput(true); // Triggers GET
connection.setDoOutput(true);// Triggers POST
connection.setRequestProperty("Authorization", key);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
System.setProperty("http.agent", "Chrome");
System.setProperty("http.proxyHost", "proxy.smmf.co.id");
System.setProperty("http.proxyPort", "8080");
out = new OutputStreamWriter(connection.getOutputStream());
out.flush();
out.close();
is = connection.getInputStream();
rdr = Json.createReader(is);
but when i try in postman it's work,
I've read on stackoverflow but still have errors like that
Someone could help me?
Thank You, a greeting,
Try modifying key variable from
String key ="Authorization : 402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
// to something like below
String key ="402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
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.
I'm running a JVM on iOS.
When I try to fetch data using a POST request from a webpage, and the connection can not be established (client sided), I get the following error:
java.net.SocketException: Invalid argument
at gnu.java.nio.VMChannel.getpeername(Native Method)
at gnu.java.nio.VMChannel.getPeerAddress(VMChannel.java:471)
at gnu.java.nio.SocketChannelImpl.isConnected(SocketChannelImpl.java:194)
at gnu.java.nio.SocketChannelImpl.read(SocketChannelImpl.java:216)
at org.apache.mina.transport.socket.nio.SocketIoProcessor.read(SocketIoProcessor.java:218)
at org.apache.mina.transport.socket.nio.SocketIoProcessor.process(SocketIoProcessor.java:198)
at org.apache.mina.transport.socket.nio.SocketIoProcessor.access$400(SocketIoProcessor.java:45)
at org.apache.mina.transport.socket.nio.SocketIoProcessor$Worker.run(SocketIoProcessor.java:485)
at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:51)
at java.lang.Thread.run(Thread.java:743)
The code that I use to do the post request (note that data might be an empty string):
URL url = new URL(urlstring);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
Also the request is executed in a separate worker-thread. The other functionality of the program is not affected when this happens.
I think it has to do with the JVM that is running. Any idea why that error is thrown? How would you prevent it from showing?
Thank you