Response from UrlConnection Java - java

So far, I have this snippet.
URLConnection connection = null;
try {
connection = (new URL("some_link")).openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
} catch (IOException e) {
}
The possible response codes are 200 and 404 and it's working fine when the response code is 200 (OK). My question is how can I find the response code received by my connection, for example: if the response code is 404, throw an exception and do smth there.

use something like this:
HttpURLConnection connection = (HttpURLConnection)new URL("URL_STRING")
.openConnection();
int statusCode = connection.getResponseCode();

Make it to a type of HTTPUrlConnection. Then you can use .getResponseCode();

Related

How to properly post url in android with java using HttpURLConnection

I try to use HttpURLConnection to send a post request to my local (xampp) server with an url like this http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2 , the server php file take param in url and send data to mysql database .
The url works fine on postman agent , and even another get method request works smooth in the android application .
Yet when i try the post method with following code :
public void postOrder() {
TextView tv = findViewById(R.id.tv1);
Thread t = new Thread( new Runnable() {
#Override
public void run() {
HttpURLConnection conn = null;
try {
String link = "http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2";
URL url = new URL(link);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(10000 /*ms*/);
conn.setConnectTimeout(15000 /*ms*/);
conn.connect();
}
catch (IOException e) {
Log.d("HTTP error: ", e.toString());
}
finally {
conn.disconnect();
}
}
} );
t.start();
}
It never sent the url and thus no data is stored to database .
And with 6 hours of trial and error , google and searching , i added this line of code :
InputStream is = conn.getInputStream();
And it finally works .
Please answer me why it only works after adding this line of code , what does it do ? I thought the url is triggered right after conn.connect();
Calling connect() only connects, but it doesn't send anything yet. Call getResponseCode() to force the request to be sent. That method is safer than getInputStream() which will throw an exception if the response is not a 2xx (in which case you'd need getErrorStream()).

How to send many/multiple post requests of JSONObjects on Android?

There's a lot of questions on StackOverflow for sending a single POST request on Android, but none of them cover cases where you're receiving lots of data from a sensor connected to your phone and need to Post Request that data as you receive it.
I'm receiving data from a sensor connected to my Android, and need to to send it to a Flask server hosted on Heroku.
public void sendToFlask(JSONObject jsonParam) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("URLHERE");
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);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
This code unfortunately errors out for creating too many files
I understand that the solution here may be to use a global HttpURLConnection but unfortunately that also gives me the error of java.net.ProtocolException: cannot write request body after response has been read This happens after I move the conn and url variables to global scope and set them in onCreate

FileNotFoundException on getInputStream from GAE address

I'm doing an Android app with an API with Python. The API is on a Google App Engine cloud and everything works fine when I tested it with Postman.
I'm trying to do a Login with a POST method. That method returns json with the user information I keep getting that error: FileNotFoundException
Here is some of my code:
try{
String account = params[0].get(0);
String password = params[0].get(1);
URL url = new URL("http", WEB_SERVICE_URL, PORT, REST_LOGIN);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
JSONObject json = jsonParser.serialJsonLogin(nomCompte, motPasse);
osw = new OutputStreamWriter(httpURLConnection.getOutputStream(),"UTF-8");
osw.write(json.toString());
osw.flush();
String body = readStream(httpURLConnection.getInputStream());
osw.close();
Log.i(TAG, "Return : " + body);
user = jsonParser.deserializeJsonUser(body);
}catch (Exception e) {
mException = e;
}finally {
if (mHttpURLConnection != null) {
mHttpURLConnection.disconnect();
}
}
return user;
At: String body = readStream(httpURLConnection.getInputStream()); I'm getting a java.io.FileNotFoundException: http://10.0.2.2:8080/login
My readStream method is fine, I tested it. If I look in my Google App Engine logs, I can see that there is no 404, or anything wrong. If I find the user I get a 201 if not a 403. So even if the error says FileNotFound, I see status code which means that actually the URL is right.
UPDATE: My API was giving me a 201 and getInputStream apparently doesn't work on 201 status. Changed my return status to 200 in my API and it works fine.

How to login to server and then hit a url on the same server to get JSON in return

Whenever I try to hit a url using java it will redirect me to login page. How can I first login then hit a specific url to get JSON in return ?
Here what I tried so far:
try {
URL url = new URL(GET_EXPENSE_FOR_VENDOR_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String response;
System.out.println("Output from Server .... \n");
while ((response = br.readLine()) != null) {
System.out.println(response);
Gson gson = new Gson();
gson.fromJson(response, ExpenseAllocationDTO[].class);
Type collectionType = new TypeToken<Collection<ExpenseAllocationDTO>>() {
}.getType();
expenseAllocationList = gson.fromJson(response, collectionType);
expenseAllocationDTODataModel = (new ExpenseAllocationDTODataModel(expenseAllocationList));
if (expenseAllocationList.isEmpty() || expenseAllocationList == null) {
expenseExists = true;
}
conn.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem
I believe the initial request is missing some headers. Only the Accept header is set.
How to solve it ?
Option #1
In order to discover the missing headers, open your favorite browser and browse to GET_EXPENSE_FOR_VENDOR_URL. Before browsing, open the webdeveloper toolbar in order to see headers sent by the browser.
Here is a sample screenshot of the webdeveloper toolbar under Chrome on Windows.
.
Option #2
If your browser doesn't have such a toolbar, you can use a tool like Fiddler for finding the missing headers.
Option #3
You can also use a tool like hurl.it in order to test the headers expected by the target server as you discover them. IMO, this tool can be more straight forward than Fiddler during the debugging phase.
Get back to your code
Once you have identified the missing headers, add them to your Java code like this:
URL url = new URL(GET_EXPENSE_FOR_VENDOR_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Missing-Header-1", "...");
conn.setRequestProperty("Missing-Header-2", "...");

code 400 error on post call with android

I am trying to call a WS method from an Android application with POST method.
What I have done:
String urlServer = GlobalSession.IP + "insert_reportByte";
Log.d("[Report]", "url address: " + urlServer);
URL url = new URL(urlServer);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data");
DataOutputStream outputStream = new DataOutputStream(
connection.getOutputStream());
outputStream.write(outputByteArray, 0, outputByteArray.length);
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.d("ServerCode", "" + serverResponseCode);
Log.d("serverResponseMessage", "" + serverResponseMessage);
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
// ex.printStackTrace();
Log.e("[Report] --- /!\\ Error: ", ex.getMessage());
}
return result;
So I am supposed to send a byte array to the service. But I have a 400 error response. My question is: how to get the details of such an issue? Because I cannot find anything in the logs of the server and it's hard to debug if I do not have the details...
The WS is defined (in ASP.NET) that way:
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "insert_reportByte",
BodyStyle = WebMessageBodyStyle.Bare)]
void insert_reportByte(byte[] image);
And the called method is the following
public void insert_reportByte(byte[] image)
{
MyEntities entities = new MyEntities();
String base64stringimage = System.Convert.ToBase64String(image,0,image.Length);
entities.insert_report("admin", "0614141.107346.2001", "test", base64stringimage, "test");
}
What did I do wrong?
Thank you !
You should change the uploadReadAheadSize and maxReceivedMessageSize parameters on your server applicationHost.config file.
Here you´ve got a thread that talks about it
http://forums.iis.net/t/1169257.aspx?Request+Entity+Too+large+413+error+
This link might be useful too as it explains why you should change the uploadReadAheadSize and maxReceivedMessageSize parameters for better handling of file uploads.
http://www.codeproject.com/Articles/521725/413-Request-Entity-Too-Large
UPDATE
Try using this library for the http calls. It seems that you're sending a bad request to the server. I don't think it has something to do with the parameters that the ws expects but the http headers sent by the android app.
https://github.com/loopj/android-async-http
Hope it helps. :)

Categories