Android cannot read http post response from flask server - java

I just wrote a simple server with flask and send a http post requset to the server from an Android App. But I failed to read the response in the Android App. The app throw an exception:
My flask code is:
#app.route('/zsj',methods = ['POST'])
def show_data():
data = request.get_json()
print request.values #json.loads(data)#request.get_json()
#data = json
#print data
return "aaaa"#jsonify({'w':'u'})
My android App just use the HttpURLConnection class to send a post and get a respones from the server, which is expected as a string: 'aaaa'. We tried to read out the string but failed.
And my Android code is
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
// Connect to the server
URL url = new URL("http://ec2-35-164-172-186.us-west-2.compute.amazonaws.com:5000/zsj");
JSONObject postDataParams = new JSONObject();
// Display command
postDataParams.put("Weather", "email");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
conn.setRequestMethod("POST");
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();
responseMessage = conn.getResponseMessage();
int responseCode=conn.getResponseCode();
responseCode2=responseCode;
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
// jtest=conn.getInputStream().read(data);
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
StringBuffer sb = new StringBuffer("");
String line="";
StringBuffer sb2 = new StringBuffer("");
// in.readLine();
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
// jtest="abc";
// jtest=sb.toString();
while((line = er.readLine()) != null) {
sb2.append(line);
break;
}
in.close();
er.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
My App code just throw an exception at
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
Anyone knows how to solve the problem

Related

Java HTTPURLConnection - Reading error response from code 400 with payload

I am trying to call an API that gives 400 on some requests.
But it has meaningful message that needs to be read.
Also i am passing a payload(json body) in the api call
My code(it takes a payload as json) and the 400 response is below
I am able to successfully read the response of 200 but issue is with 400
public static void blahblah (String input, String CustomerID, String endpoint, String dateNameFolder) throws UnknownHostException
{
try {
URL url = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
File fileObj = new File(CustomerID + ".json");
if (!fileObj.exists()) {
fileObj.createNewFile();
FileWriter dataWriter = new FileWriter(CustomerID + ".json");
dataWriter.write(sb.toString());
dataWriter.close();
} else {
FileWriter dataWriter = new FileWriter(CustomerID + ".json");
dataWriter.write(sb.toString());
dataWriter.close();
}
conn.disconnect();
}catch (MalformedURLException e) {
l
log.info(e);
}
catch (IOException e) {
log.error("Error in Validating Request to Catalog for Customer ID(400 Bad Request) : " + CustomerID ) ;
log.info(e);
}
}
Sample output of 400 bad request :
<Response>
<StatusCode>BadRequest</StatusCode>
<ErrorCode>OrderRequestInvalid.InvalidCharacteristicUse</ErrorCode>
<Message>Characteristic ID cannot be found in the specification: { EntityUniqueCode: CS_0aefdfec-022e-4ac9-a84b-83c8ea2e0fd0, CharacteristicID: 76c4e767-ce7b-4675-a178-d832839b322f}</Message>
<Context>
<EntityUniqueCode>CS_0aefdfec-022e-4ac9-a84b-83c8ea2e0fd0</EntityUniqueCode>
<CharacteristicID>76c4e767-ce7b-4675-a178-d832839b322f</CharacteristicID>
</Context>
</Response>
You need to choose correct stream depending on your response status. here is an example how you can do this:
BufferedReader br = null;
int statusCode = conn.getResponseCode();
if (statusCode>299){
br = new BufferedReared(new InputStreamReader(conn.getErrorStream()));
} else {
br = new BufferedReared(new InputStreamReader(conn.getInputStream()));
}

Parse JSONArray in Android Studio

I try to get parse an JSONArray from a PHP-Script in AndroidStudio. I get this JSON Response from my PHP script:
[{"0":"Firstname","meta_value":"Firstname"},{"0":"Lastname","meta_value":"Lastname"},{"valid":"1"},{"entered":"5"}]
Now I try to parse the JSONArray to get the value meta_value so I want to get "Lastname" and "Firstname".
But there must be an error in my code because I get as response: Exception: No value for meta_value
public class SendPostRequest extends AsyncTask<String, Void, String> {
String data ="";
String dataParsed = "";
String singleParsed ="";
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("https://sample.com/code2.php"); // here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("sdata", scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
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();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
data = data + line;
sb.append(line);
break;
}
in.close();
JSONArray reader2 = new JSONArray(data);
for(int i =0 ;i <reader2.length(); i++){
JSONObject JO = (JSONObject) reader2.get(i);
singleParsed = "Name:" + JO.get("meta_value") + "\n";
dataParsed = dataParsed + singleParsed +"\n" ;
}
return dataParsed;
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
Please dont mark my Answer as duplicate because I searched for 2 weeks and but havent found an Answer! Thank you:)
I would suggest you to use GSON for serializing and deserializing your JSON responses. It makes it quite easy to handle then. GSON.
Sample:
new Gson().fromJson("YourJsonHere",JsonElement.class);
Cheers Tarik

Http post request parameters limit

I'm try to pass 19(images) parameters to htttp post request, but when I put more then 9 params, my app don't do the upload to server, I recheck all the code and is ok, server side is ok also.
#Override
protected String doInBackground(Void... params) {
Log.d("SETIMAGE", "IMAGEM DOINBACKGROUND INIT");
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_ID,id);
param.put(KEY_CHAMADO,chamado);
param.put(FACHADA,imageFachada);
param.put(RADIO,imageRadio);
param.put(SUPORTE,imageSuporte);
param.put(MASTRO,imageMastro);
param.put(ISOLAMENTO,imageIsolamento);
param.put(INFRAEXT1,imageInfraExt1);
param.put(INFRAEXT2,imageInfraExt2);
param.put(INFRAINT1,imageInfraInt1);
param.put(INFRAINT2,imageInfraInt2);
param.put(CONECTOREXT,imageConectorExt);
param.put(CONECTORINT,imageConectorInt);
param.put(SALATEC,imageSalaTec);
param.put(RACK,imageRack);
param.put(IDU,imageIDU);
param.put(TOMADAIDU,imageTomadaIDU);
param.put(AZIMUTE,imageAzimute);
param.put(GPS,imageGPS);
param.put(MTCABOEXT,imageMtCaboExt);
param.put(MTCABOINT,imageMtCaboInt);
String result = rh.sendPostRequest(UploadUrl, param);
Log.d("RESULT", result);
return result;
}
This is via RequestHandler.class
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(150000);
conn.setConnectTimeout(150000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null) {
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
I need to pass all images to upload to server. But it's ok only when I pass 9 param.put
You should consider using Retrofit, which allows to upload huge size files in chunks and has more flexibility than most libraries.

How to connect to MovieDB API webservice?

I am new to webservice and I am in the learning phase. Not much of the online content gives information about the use of MovieDB API webservice. Well for not I am just focusing on trying to get a movie information on the screen.
So the as per the API I am requesting the information and I am getting the JSON response when I paste http://api.themoviedb.org/3/movie/550?api_key=MYKEY in the browser.
I want to write a webservice using JAVA,SOAP to parse the JSON and fetch the required information. I tried using HttpURLConnection and then use BufferedReader but its not working.
Kindly suggest me some better options. Any links/blogs will be helpful.
This is the code snippet.
public class TestJSON {
/**
* #param args
*/
public static void main(String[] args) {
try{
URL url = new URL("http://api.themoviedb.org/3/movie/550?api_key=MYKEY/3/movie/550");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
String input = "";
OutputStream os = con.getOutputStream();
os.write(input.getBytes());
os.flush();
if (con.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ con.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
}
catch(MalformedURLException m){
System.out.println("Malformed URL");
}
catch(IOException ioe){
System.out.println("IO exception");
}
}
}
Thanks in advance.
Zingo
Try this code to read the output from the url:
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();

Catch errors of HttpUrlConnection in AsyncTask

I'm searching for a best practice to handle errors in an HttpURLConnection especially if the host is not available. How did I have to change my source?:
protected String doInBackground(String... strings) {
URL aURL;
String line;
HttpURLConnection connection;
BufferedReader reader;
StringBuilder stringBuilder = null;
try {
aURL = new URL(strings[0]);
connection = (HttpURLConnection) aURL.openConnection();
InputStream aInputStream = connection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(aInputStream);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
} catch (IOException e) {
Log.d("svc", e.toString());
}
return stringBuilder.toString();
}
you will get different responsecode using connection.getResponseCode()
Check for the response codes for host not available and you will be set.

Categories