I want to get a json string from my remote server.
I have a very weird problem as I manage to get my json string only thanks to getErrorStream but not thanks to getInputStream.
Here is my code:
URL url = new URL("my_https_url");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseStatusCode = connection.getResponseCode(); // ERROR 500 HERE
InputStream inputStream;
if(responseStatusCode != HttpsURLConnection.HTTP_OK ) {
inputStream = connection.getErrorStream(); // I pass through here
} else {
inputStream = connection.getInputStream();
}
response = IoUtils.readAll(inputStream); // I get my json string properly after being passed through getErrorStream()
If I remove my 'if statement' and try to do only:
inputStream = connection.getInputStream()
I get a fileNotFoundException.
Anybody has a clue how to solve this issue?
Thanks.
Related
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 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
In my application, I am trying get the response using POST request. The response server is sending me in Json format. But after adding the properties, it is returning me the response code as 411 (i.e issue with content length).
I have already added the content length. Then where is the issue i am not getting. Here is my code:
String url = "https://xxx:8243/people/v3";
STRURL = url + HttpComm.getConnectionString().trim();
StringBuffer postData = new StringBuffer();
HttpConnection httpConnection = null;
try {
httpConnection = (HttpConnection) Connector.open(STRURL);
} catch (IOException e1) {
e1.printStackTrace();
};
try {
httpConnection.setRequestMethod("POST");
postData.append("?username="+user);
postData.append("&password="+password);
String encodedData = postData.toString();
byte[] postDataByte = postData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type","application/json");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
DataOutputStream dos = new DataOutputStream(out);
out.write(postData.toString().getBytes());
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
if (statusCode != HttpConnection.HTTP_OK)
{
}
Updated Code :
HttpConnection httpConnection = null;
try {
httpConnection = (HttpConnection) Connector.open(STRURL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
try {
httpConnection.setRequestMethod("POST");
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
postData.append("username", user);
postData.append("password", password);
byte[] postDataByte = postData.getBytes();
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
out.write(postDataByte);
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
There are a few things that don't look quite right here. I would recommend trying this:
httpConnection.setRequestMethod("POST");
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
postData.append("username", user);
postData.append("password", password);
byte[] postDataByte = postData.getBytes();
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
DataOutputStream dos = new DataOutputStream(out);
out.write(postDataByte);
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
if (statusCode != HttpConnection.HTTP_OK)
What I changed:
As #samlewis said, the code was creating a variable to hold the post data bytes, but then was not using it when it called out.write().
The code set the content type to JSON, but it was not sending JSON. The request was simply two parameters. The response may be JSON, but you don't specify that in the request's Content-Type parameter.
The username/password parameters were encoded just using strings. Normally, it's best to use the URLEncodedPostData class to hold your POST parameters.
If you are going to use strings, I think it was still incorrect to add a ? to the front of the username parameter. If you want to encode parameters in a GET URL, then you use https://xxx:8243/people/v3?username=user&password=password. But, this code was using POST, not GET.
There was also an unused encodedData variable.
I'm trying to use twitter api in the following way:
String urlAdd = "https://api.twitter.com/1/following/ids.json?user_id=1000123";
URL url = new URL(urlAdd);
URLConnection urlConnection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
getInputStream input stream throws IOException, it happens because i've reached my request limit.
I want to be able to distinghuish between request limit error and other errors. Twitter returns error message in json format, but i can't read it because of the thrown exception.
Any ideas on how can I fetch the error message?
I found a way to do it:
String urlAdd = "https://api.twitter.com/1/following/ids.json?user_id=1000123";
URL url = new URL(urlAdd);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));
As the title says ... I have tried to use the following code to execute a PHP script when user clicks a button in my Java Swing application :
URL url = new URL( "http://www.mywebsite.com/my_script.php" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
But nothing happens ... Is there something wrong ?
I think you're missing the next step which is something like:
InputStream is = conn.getInputStream();
HttpURLConnection basically only opens the socket on connect in order to do something you need to do something like calling getInputStream() or better still getResponseCode()
URL url = new URL( "http://google.com/" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
// do something with the data here
}else{
InputStream err = conn.getErrorStream();
// err may have useful information.. but could be null see javadocs for more information
}
final URL url = new URL("http://domain.com/script.php");
final InputStream inputStream = new InputStreamReader(url);
final BufferedReader reader = new BufferedReader(inputStream).openStream();
String line, response = "";
while ((line = reader.readLine()) != null)
{
response = response + "\r" + line;
}
reader.close();
"response" will hold the text of the page. You may want to play around with the carriage return (depending on the OS, try \n, \r, or a combination of both).
Hope this helps.