Android - Exceptions while sending post request to the server - java

In my android project I have a class for the HTTP requests to my server. There I have methods for sendGet, sendPost and sendPut. Here is the code for the sendPost method:
public JSONObject sendPost(String urlString, String urlParameters) {
URL url;
JSONObject jObj = null;
String json = "";
try{
url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
json = sb.toString();
} catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
try{
jObj = new JSONObject(json);
}
catch (JSONException e){
e.printStackTrace();
}
System.out.println(jObj);
return jObj;
}
It should return the server response as a JSONObject. If I send a post to my server, I get the following exceptions:
java.io.FileNotFoundException: http://... (In the line where I create the BufferedReader)
org.json.JSONException: End of input at character 0 of (In the line where I do jObj = new JSONObject(json);)
But if I copy the url to my browser there are no problems with it. And it seems like everything is working, because my server has received and processed the request. But why I get these errors and an empty JSONObject as result?
EDIT:
On my node.js server I send responses in the following format:
res.status(200).json({ success: "true" });
or
res.status(400).json({ success: "false", message:"..." });
EDIT 2:
After #greenapps comment I changed my code a bit:
...
json = sb.toString();
jObj = new JSONObject(json);
br.close();
wr.flush();
wr.close();
} catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace();
}
return jObj;
Now the JSONException is gone, but the FileNotFoundException is still there and the jObj is still empty when it got returned.

I had a bug in my node.js server and the response code of the server was 502. And the BufferedReader only works with a 200 status code. Thats why I got the exceptions. Now I have a if around the BufferedReader:
if(connection.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
jObj = new JSONObject(json);
br.close();
}else{
json = "{ success: \"false\" }";
jObj = new JSONObject(json);
}

Related

POST JSON to Server and Receive Response

I have a class, called FindMeARestaurantDAO, which contains methods that will make network calls to a server with AsyncTask inner classes in my Activity. I am having issues with my POST request Method, which is as follows:
#Override
public String findMeARestaurant(List<CheckboxDTO> filters) {
String inputLine;
String errors;
String result;
try
{
// For each CheckboxDTO, get the Id and add it to JSONArray
JSONArray checkboxJSONArray = new JSONArray();
for (CheckboxDTO checkbox : filters)
{
try
{
// Create JSONObject
JSONObject object = new JSONObject();
// Build the object
object.put("id", checkbox.getId());
// Add object to JSONArray
checkboxJSONArray.put(object);
}
catch (Exception e)
{
e.printStackTrace();
}
}
// Put JSONArray into wrapping JSONObject
JSONObject serverObject = new JSONObject();
try
{
// Create wrapping JSONObject
serverObject.put("filtersIds", checkboxJSONArray);
}
catch (Exception e)
{
e.printStackTrace();
}
// Create URL object to hold URL
URL findMeARestaurantURL = new URL(findMeARestaurantsURL);
// Create connection to server
HttpURLConnection connection = (HttpURLConnection) findMeARestaurantURL.openConnection();
// Set request method and timeouts
connection.setRequestMethod(FIND_RESTAURANT_REQUEST_METHOD);
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setChunkedStreamingMode(0);
connection.setDoOutput(true);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
// Connect to server
connection.connect();
// Create Writer
Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(String.valueOf(serverObject));
// Close Writer
writer.close();
// Create InputStreamReader to read response from server
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
// Create BufferedReader to read through InputStream
BufferedReader reader = new BufferedReader(streamReader);
// Create StringBuilder to hold our result
StringBuilder stringBuilder = new StringBuilder();
// Check if the line read is null
while ((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
// Close out InputStream and BufferedReader
reader.close();
streamReader.close();
// Set result to stringBuilder
result = stringBuilder.toString();
connection.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
return result;
}
The method is POST and it appears to send the JSON serverObject to the server when I run my application, but it fails on the InputStreamReader and returns a FileNotFoundException. The server was set up by a partner for this project and says this portion of the API should be working. Am I missing something for the POST request? Do I need to be doing something differently for reading the server's response? Any help would be greatly appreciated.
The solution to this issue was in how I sent the data to the server in a POST request. I had to send my filters' Ids to the server by adding them to my URL before establishing the connection. My modified method iterates through each CheckboxDTO and catches the Id, then adds it to an array, which is then added to the URL:
#Override
public String findMeARestaurant(List<CheckboxDTO> filters) {
String inputLine;
String result;
try
{
// For each CheckboxDTO, get the Id and add it to String Array
int checkboxArray[] = new int[filters.size()];
int i = 0;
for (CheckboxDTO checkbox : filters)
{
try
{
int id = checkbox.getId();
checkboxArray[i] = id;
i++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
// Add filters to end of URL for POST Request
findMeARestaurantsURL += "?filterIds=";
for (i = 0; i < checkboxArray.length; i++)
{
if (i+1 != checkboxArray.length)
{
findMeARestaurantsURL += checkboxArray[i] + ",";
}
else
{
findMeARestaurantsURL += checkboxArray[i];
}
}
// Create URL object to hold URL
URL findMeARestaurantURL = new URL(findMeARestaurantsURL);
// Create connection to server
HttpURLConnection connection = (HttpURLConnection) findMeARestaurantURL.openConnection();
// Set request method and timeouts
connection.setRequestMethod(FIND_RESTAURANT_REQUEST_METHOD);
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setChunkedStreamingMode(0);
connection.setDoOutput(true);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
// Connect to server
connection.connect();
// Create InputStreamReader to read response from server
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
// Create BufferedReader to read through InputStream
BufferedReader reader = new BufferedReader(streamReader);
// Create StringBuilder to hold our result
StringBuilder stringBuilder = new StringBuilder();
// Check if the line read is null
while ((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
// Close out InputStream and BufferedReader
reader.close();
streamReader.close();
// Set result to stringBuilder
result = stringBuilder.toString();
connection.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
return result;
}
The server uses the Spring framework, and according to my partner, did not use a JSONObject.

HTTP response not giving output

I am working on an application that interacts with a room security control device.
I want to get devices information from API. I am using HttpUrlConnection and POST method. It hits the API and I get 200 OK response but I get the out
"{"json":{"control":{"cmd":"getdevice","uid":256}}} doesn't exist"
I have tried all the solutions from stackoverflow and other platforms but it's not giving the output.
Moreover I have tested this API on Postman and it's working there and giving the device information.
Here is the code:
public class HTTPRequestTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
String username = "admin";
String password = "888888";
URL url = null;
try {
url = new URL("http://192.168.100.25/network.cgi");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
HttpURLConnection httpRequest = null;
try {
httpRequest = (HttpURLConnection) url.openConnection();
httpRequest.setRequestMethod("POST");
httpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setDoInput(true);
httpRequest.setDoOutput(true);
android.util.Base64.encode(authString.getBytes(), android.util.Base64.DEFAULT);
httpRequest.addRequestProperty("Authorization", "Basic " + "YWRtaW46ODg4ODg4"); // This is auth bytecode
httpRequest.connect();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONObject jsonObjectControl = new JSONObject();
jsonObjectControl.put("cmd","getdevice");
jsonObjectControl.put("uid",256);
jsonObject.put("control",jsonObjectControl);
json.put("json", jsonObject);
String encodedData = URLEncoder.encode( json.toString(), "UTF-8" );
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpRequest.getOutputStream()));
writer.write(encodedData);
writer.flush();
BufferedReader bufferedReader = null;
bufferedReader = new BufferedReader
(new InputStreamReader(httpRequest.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
do {
line = bufferedReader.readLine();
sb.append(line);
Log.i("Output line: ",sb.toString());
}
while(bufferedReader.readLine()!=null);
bufferedReader.close();
int responseCode = httpRequest.getResponseCode();
String resMsg = httpRequest.getResponseMessage();
String result = sb.toString();
Log.d("Output: ","--"+result);
Log.d("Response Code: "+responseCode, "!!");
Log.d("Response MSG ","--"+resMsg);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Android not able to recognize different language Fonts

Made an app to translate different words to different Language
Using Yandex converter getting proper results on Browser
converting Kiss
RESULTS as JSON object is
{"code":200,"lang":"en-hi","text":["चुम्बन"]} //proper
but while getting result on app
RESULT
{"code":200,"lang":"en-hi","text":["à¤à¥à¤®à¥à¤¬à¤¨"]}
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
geJSONFromUrl function
public JSONObject getJSONFromUrl(String urlSource) {
//make HTTP request
try {
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Read JSON data from inputStream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
return jObj;// return JSON String
}
}
Is there any way i can get proper results?
Please HelpRegards
changed
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
to
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

How to send such json post request in java with param in the url?

I have such a data. I don't know how to write it in java to send a post JSON request. Please help me! I can do it with curl in Windows, the code is:
curl -X POST -H "Content-Type:application/json" -d "[{\"hostId\": \"01a31fc518c44166afe29a8694f4b3e8\",\"host\": \"WIN-PC_tttqa\",\"metric\": \"system.cpu.used1232\",\"timestamp\": 1457577649000,\"value\": 0,\"tags\": [\"location:aa\",\"level:high\"],\"type\": \"gauge\"}]" http://ip:port/openapi/v2/datapoints?api_key=fe01ce2a7fbac8fafaed7c982a04e229
data format
You can see the data format in the img link of "data format", please show me the code, then I will try it immediately.
This is my test function:
public void sendPost() throws JSONException {
HttpURLConnection connection = null;
try {
// 创建连接
URL url = new URL(ADD_URL);
connection = (HttpURLConnection) url.openConnection();
// 设置http连接属性
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// 设置http头 消息
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setRequestProperty("Accept", "application/json");
// 添加 请求内容
JSONArray jsonArray = new JSONArray();
JSONObject json = new JSONObject();
json.put("api_key", "fe01ce2a7fbac8fafaed7c982a04e229");
json.put("hostId", "01a31fc518c44166afe29a8694f4b3e8");
json.put("host", "WIN-PC240");
json.put("metric", "system.cpu.used1232");
json.put("value", 0);
JSONArray array = new JSONArray();
array.put("location:aaa");
array.put("level:high");
json.put("tags", array);
json.put("type", "gauge");
jsonArray.put(json);
System.out.println(jsonArray.toString());
OutputStream out = connection.getOutputStream();
out.write(jsonArray.toString().getBytes());
out.flush();
out.close();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
reader.close();
// // 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I made a mistake. I thought post request can't follow "?param=..." in the URL. I just need to put the "api_key" in the URL instead of putting it in the JSON parameters.

pass parameters via http post method

I have two text boxes, 1 for username and the other for password.
I wanted to pass what the user enters into the edit texts with the post method
String request = "https://beta135.hamarisuraksha.com/web/webservice/HamariSurakshaMobile.asmx/getIMSafeAccountInfoOnLogon";
URL url;
try {
url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;");// boundary="+CommonFunctions.boundary
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
/*
* System.out.println("\nSending 'POST' request to URL : " +
* url); System.out.println("Post parameters : " +
* urlParameters);
*/
System.out.println("Response Code : " + responseCode);
InputStream errorstream = connection.getErrorStream();
BufferedReader br = null;
if (errorstream == null) {
InputStream inputstream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
} else {
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String nachricht;
while ((nachricht = br.readLine()) != null) {
response += nachricht;
}
// print result
// System.out.println(response.toString());
return response.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
if i am getting your question correctly , you need to pass your parameters to a web service. in my case i have implemented a method to get the web service response by giving the url and the values as parameters. i think this will help you.
public JSONObject getJSONFromUrl(JSONObject parm,String url) throws JSONException {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
/*JSONObject parm = new JSONObject();
parm.put("agencyId", 27);
parm.put("caregiverPersonId", 47);*/
/* if(!(jObj.isNull("d"))){
jObj=null;
}
*/
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
HttpEntity body = new StringEntity(parm.toString(), "utf8");
httpPost.setEntity(body);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
/* String response = EntityUtils.toString(httpEntity);
Log.w("myApp", response);*/
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// JSONObject jObj2 = new JSONObject(json);
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
this method take two parameters. one is the url, other one is the values that we should send to the web service. and simply returns the json object. hope this will help you
EDIT
to pass your username and password just use below code
JsonParser jp = new JsonParser(); // create instance for the jsonparse class
String caregiverID = MainActivity.confirm.toString();
JSONObject param = new JSONObject();
JSONObject job = new JSONObject();
try {
param.put("username", yourUserNAme);
job = jp.getJSONFromUrl(param, yourURL);

Categories

Resources