POST JSON to Server and Receive Response - java

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.

Related

Getting Empty response From PHP web API in android

I'm using Asynctask For network call in android Studio.I have php web API's I dont know why but Some of them Not Working in android .
Following is My AsyncTask Class...
private class AsyncAddfriend extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected String doInBackground(String... params) {
try {
url = new URL("http://ishook.com/users/friends/send_friend_request_json/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("sessionId", params[0])
.appendQueryParameter("UserId", params[1])
.appendQueryParameter("friendId", params[2]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
}
I'm using same Code for other API's also they all are working fine but this api is not working.
I have Tested This API in post man its working but in not working android .
Hope You will understand My problem....

HttpURLConnection always failing with 401

I'm trying to use HttpURLConnection for connecting to server from Android app which I'm developing. For now, I'm testing the connection code not in an app but as a plain java program with main class. I guess this doesn't make any difference as far as HttpUrlConnection.
Please examine the code snippet. Another issue is even errorStream is throwing null. This I feel is because of malformed URL.
private static String urlConnectionTry() {
URL url; HttpURLConnection connection = null;
try {
String urlParameters = "email=" + URLEncoder.encode("email", "UTF-8") +
"&pwd=" + URLEncoder.encode("password", "UTF-8");
//Create connection
url = new URL("http://example.com/login");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("uuid", getUuid());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
private static String getUuid() {
try {
Document doc=Jsoup.connect("http://example.com/getUuid").get();
Elements metaElems = doc.select("meta");
for (Element metaElem : metaElems) {
if(metaElem.attr("name").equals("uuid")) {
return metaElem.attr("content");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You're probably receiving 401 because the credentials that was sent to the server is not authorized- it's probably not registered or the password is incorrect.
As for the null error stream, take a look at this SO answer.
If the connection was not connected, or if the server did not have an error while connecting or if the server had an error but no error data was sent, this method will return null.
It is probably better if you check first the response code using HttpUrlConnection#getResponseCode(). Decide on whether you'll be checking the contents of the error stream based on the response code you get.

HttpURLConnection response is not working

In my project I have url
like:
localhost:8080/myproject/examples/12
It contains Json values..To access this field Need to put access key as Header.
Now, What I have done is that :
private String doHttpUrlConnectionAction(String desiredUrl)
throws Exception
{
URL url = null;
BufferedReader reader = null;
StringBuilder stringBuilder;
try
{
// create the HttpURLConnection
url = new URL(desiredUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// just want to do an HTTP GET here
connection.setRequestMethod("GET");
// connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("API-KEY", "value");
// uncomment this if you want to write output to this url
connection.setDoOutput(true);
// give it 15 seconds to respond
connection.setReadTimeout(15*1000);
connection.connect();
// read the output from the server
// reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
// close the reader; this can throw an exception too, so
// wrap it in another try/catch block.
if (reader != null)
{
try
{
reader.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
this code returns output :
Response Code : 200
<table border="0" cellpadding="4" cellspacing="0"><thead><tr><th>status</th><th>statusCode</th><th>data</th></tr></thead><tbody><tr><td statusCode="200" status="1">Array</td></tr></tbody></table>
But when I am accessing this code in httclient, I am getting value properly..
public String ReadHttpResponse(String url){
StringBuilder sb= new StringBuilder();
HttpClient client= new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.addHeader("API-KEY", "value");
try {
HttpResponse response = client.execute(httpget);
StatusLine sl = response.getStatusLine();
int sc = sl.getStatusCode();
if (sc==200)
{
HttpEntity ent = response.getEntity();
InputStream inpst = ent.getContent();
BufferedReader rd= new BufferedReader(new InputStreamReader(inpst));
String line;
while ((line=rd.readLine())!=null)
{
sb.append(line);
}
// System.out.println(sb.toString());
}
else
{
System.out.println("I didn't get the response!");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
Here,I am getting output properly..
Where is the problem in HttpUrlConnection?? What am I doing wrong here?? I have to use HttpUrlConnection.Please guys help me out..
You can make code logic like this for both request POST and GET. It helps to reduce code complexity. You can make one method for that and pass parameter to it as needed for GET and POST methods.
HttpURLConnection urlConnection = null;
try {
// http client
murl=new URL(url);
urlConnection = (HttpURLConnection) murl.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json;odata=verbose");
urlConnection.setRequestProperty("Accept", "application/json;odata=verbose");
// Checking http request method type
if (method == POST) {
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
if(!jsondata.equals("null")) {
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsondata);
writer.flush();
writer.close();
os.close();
}
} else if (method == GET) {
// appending params to url
urlConnection.setRequestMethod("GET");
}
resCode = urlConnection.getResponseCode();
Log.i("TAG", "response code=>" + resCode);

Receiving null Value while using POST method in servlet?

I want to send a string by using POST method in servlet so that it can communicate with other servlet application present in other domain. But I am receiving null in my Input steam object.
My Code:
String content = "10 141 nahush123 01";
URL url = new URL("http://52.220.37.12:8080/servers/servers");
System.out.println(url.toString());
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoInput(true);
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
OutputStream os = httpCon.getOutputStream();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
out.write(content);
//br = BufferReader(out);
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
writer.println(httpCon.getResponseMessage());
httpCon.connect();
br = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
//reading response
//String resp;
//if(br != null){
content = br.readLine();
//}
System.out.println(content);
writer.println(content);
out.flush();
writer.flush();
writer.close();
out.close();
os.close();
Copy pasted your code in my servlet worked fine
Check that you overrided doPost method in the servlet
Check that you that your post metod work fine and return value, I use "DHC Rest Client" plugin for chrome. It is very cool tool
Try to remove httpCon.connect() line. It is not necessary.
From oracle docs about connect() method:
Operations that depend on being connected, like getContentLength, will
implicitly perform the connection, if necessary.
Operations getResponseMessage, getResponseCode perform the connection.
UPDATED
I tried to test with my local test url and it works. Then i tried with your url and it does not work.
You need to flush output stream before use input stream.
This code work and return "0#5#26#Temperature#Living_Room#555555581#0+0#7#0#Room1#Master_bedroom#555555581#1+1#7#0#Door1#Living_Room#555555581#2+1#6#0#frontdoor#Living_Room#555555581#2+0#6#0#doorback#Balcony#555555581#2+"
PrintWriter writer = res.getWriter();
String content = "10 141 nahush123 01";
URL url = new URL("http://52.220.37.12:8080/servers/servers");
System.out.println(url.toString());
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoInput(true);
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
OutputStream os = httpCon.getOutputStream();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
out.write(content);
out.flush();
//br = BufferReader(out);
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
writer.println(httpCon.getResponseMessage());
//httpCon.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
//reading response
//String resp;
//if(br != null){
content = br.readLine();
//}
System.out.println(content);
writer.println(content);
writer.flush();
writer.close();
out.close();
os.close();
Try with getparameter() function in the servlet
Call this method with your pass string parameter:
public String postData(String reqStr) {
ObjectOutputStream objOS = null;
ObjectInputStream objIS = null;
HttpURLConnection servletCon = null;
try {
if (reqStr != null) {
Thread.sleep(1000);
objOS.writeObject(reqStr);
} else {
throw new Exception("request is null.");
}
} catch (Exception ex) {
logger.error("Failed to send request to server.", ex);
}
String response = null;
try {
objIS = new ObjectInputStream(servletCon.getInputStream());
response = (String) objIS.readObject();
} catch (Exception ex) {
logger.error("Failed to get response from server.", ex);
response = null;
}
return response;
}
Initializing Connection like you but calling differently:
public void initializeUrlConnection(String servletURL, String contentType, String method) {
try {
logger.debug("Servlet URL " + servletURL);
url = new URL(servletURL);
servletCon = (HttpURLConnection) url.openConnection();
servletCon.setUseCaches(false);
servletCon.setDefaultUseCaches(false);
servletCon.setDoInput(true);
servletCon.setDoOutput(true);
servletCon.setRequestProperty("Content-Type", contentType);
servletCon.setRequestMethod(method);
objOS = new ObjectOutputStream(servletCon.getOutputStream());
} catch (IOException ex) {
logger.error("Failed to initialize Http Connection.", ex);
}
}
First of call initialize connection method with required parameter:
Object.initializeUrlConnection(url, contentType,method);
then call posDataMethod with your string/json parameter:
Object.postData(str);

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.

Categories

Resources