How to set json array in url with get method in android? - android

http://192.168.0.14/something/storeAnswerGet?longitude=20.49158053365199&latitude=44.798944935485885&answers="[{\"id\":3,\"id_question\":7,\"user_id\":1,\"answer\":\"Beograd\"},{\"id\":3,\"id_question\":7,\"user_id\":1,\"answer\":\"Valjevo\"},{\"id\":3,\"id_question\":8,\"user_id\":1,\"answer\":\"Da\"}]"
Problem is after &answers= it is not recognized as part of url,
that is a formatted JsonObject in string.

Explained here:
https://stackoverflow.com/a/27578923/1088975
Basically you have 2 options
Send data with POST method
Encode text and send with GET

Basically storeAnswer shall be post request and payload to be added on the request body with json format.
public void sendAnswerRequest(){
try {
URL url = new URL("http://192.168.0.14/something/storeAnswerGet");
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);
JSONObject jsonParam = new JSONObject();
jsonParam.put("latitude", 44.798944935485885);
jsonParam.put("longitude", 20.49158053365199);
JSONArray answers = new JSONArray();
JSONObject answer = new JSONObject();
answer.put("id",3);
answer.put("id_question",7);
answer.put("user_id",1);
answer.put("answer","Beograd");
answers.put(answer); // Add all answers to answer array..
jsonParam.put("answers",answers);
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();
}
}

Related

Some character didn't post with Json Post - getting 500 reponse

I have prepared one API, and I want to send one specific data with json posting.
My code works fine during working with Fiddler or site side.
But the problem is why some character didn't send, when we use Android version as a client device.
For example:
string a="mn✈" // correct on any device (android,site,Fiddler,...)
string b="mn✉" //correct on any device except(android) //getting 500 reponse
String requestURL = Utils.SERVER_URL + "PostJsonFeatures";
HttpURLConnection conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject postDataParams = new JSONObject();
postDataParams.put("Features", getAttributes());
postDataParams.put("productId", productId);
postDataParams.put("groupId", catId);
postDataParams.put("brandId", PrefManager.getInstance(context).getCompanyId());
postDataParams.put("languageId", PrefManager.getInstance(context).getLanguageApi());
DataOutputStream printout = new DataOutputStream(conn.getOutputStream ());
printout.write(postDataParams.toString().getBytes());
printout.flush ();
printout.close ();
You can decode to string and pass in url.
String parseString = URLDecoder.decode(URLEncoder.encode(myString, "UTF-8"), "ISO-8859-1");

Android HttpURLConnection set GET Request method

I would like to send HTTP Request with GET method, but I can't set the GET method.
Here's my code:
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("p1", "123")
.appendQueryParameter("p2", "123");
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();
Log.e("ERROR", conn.getResponseMessage());
Log.e("ERROR", conn.getRequestMethod());
Log.e("ERROR", String.valueOf(conn.getResponseCode()));
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
In the code, I set GET method, but on the log, request method is POST:
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ Method Not Allowed
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ POST
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ 405
What is a problem?
the problem is
conn.setDoOutput(true);
when set to true the request method is changed to POST, since GET or DELETE can't have a request body

how can send a json frame to mysever hear i can reserve a json and i wnd send the data

I posted the code I used for reading the data from my server but I don't know how to send a json frame to the server.
I want to send the data string.
try {
URL url = new URL(params[0]);
con = (HttpURLConnection)url.openConnection();
con.connect();
InputStream in = con.getInputStream();
red = new BufferedReader(new InputStreamReader(in));
String line = "";
buffer = new StringBuffer();
while ((line=red.readLine())!= null){
buffer.append(line);
}
return buffer.toString();
I would assume that you are trying to post some JSON Object to a URL,
While using HttpURLConnection for connection you can set to its instance that this is a POST header request, if you are indeed posting something on that URL.
After that you can use DataOutputStream instance to write(POST) your JSON data something like this.
I have written a snippet which you can check, the code is also available on Github
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
/**
* Kindly change this url string with your own, where you want to post your json data
*/
URL url = new URL("");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
// when you are posting do make sure you assign appropriate header
// In this case POST.
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
// like this you can create your JOSN object which you want to send
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("email", "dddd#gmail.com"); //dummy data
jsonObject.addProperty("password", "password");// dummy data
// And this is how you will write to the URL
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
Log.d("TAG", "" + IOUtils.toString(httpURLConnection.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
This code uses apache-common-io, to get the String from the input stream, if you would like you can change that.

POST function for REST service returns empty response

I'm trying to do a post method for a REST service, but I'm not getting any response from server:
public JSONObject postValues (String strUrl, String strJsonArray) throws Exception{
JSONObject jsonObject = null;
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
strJsonArray = "data=" + strJsonArray;
Log.e("result",""+strJsonArray);
OutputStream os = conn.getOutputStream();
os.write(strJsonArray.getBytes());
os.flush();
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
Log.e("output",output);
sb.append(output);
}
Log.e("output",sb.toString());
jsonObject = new JSONObject(sb.toString());
conn.disconnect();
return jsonObject;
}
When I see my logCat a get:
output {}
I know that the server is working right because I'm using the "advanced REST client" plugin of google chrome. If I call the URL manually (using the plugin of course)I get the desired answer:
{"message":"OK","code":200}
But if I try to use my function, my strJsonArray is inserted but I get an empty respond from server.
Is there anything wrong with my code?.
Everything looks good...
You could use Wireshark to capture the packets sent to and received from the server using an emulator and the chrome rest client. Then you can compare them and maybe find out what's wrong.
You could also check if theres something in the error stream (conn.getErrorStream()).

POSTing JSON and retrieving a response in Android

I am trying to post a JSON message to a site and to retrieve a JSON message back.
java.net.ProtocolException: method does not support a request body: POST
Does anyone know what is wrong? Thanks in advance
HttpURLConnection conn=null;
try{
URL url=new URL(urlString);
String userPassword = userName +":" + passWord;
byte[] bytes=Base64.encode(userPassword.getBytes(),Base64.DEFAULT);
String stringEncoding = new String(bytes, "UTF-8");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "Basic " + stringEncoding);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
Log.i("Net", "length="+conn.getContentLength());
Log.i("Net", "contentType="+conn.getContentType());
Log.i("Net", "content="+conn.getContent());
conn.connect();
}catch(Exception e){
Log.d("Url Formation Connection", e.toString());
}
//output{
try{
String requestString="{“ ";
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(requestString.toString());
wr.flush();
//input{
BufferedReader rd = null;
String response=" ";
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer responseBuff = new StringBuffer();
while ((line = rd.readLine()) != null) {
// Process line...
responseBuff.append(line);
}
response = responseBuff.toString();
Log.d("response", response);
}catch(Exception e){
Log.d("buffer error", e.toString());
}finally {
if (is != null) {
try {
wr.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It could be that the server you're connecting to doesn't allow POST operations. I would try a GET request first, to see if you have permissions for that web service method.
Also, you could try your luck with a simpler HttpClient, although I haven't tested this solution myself: http://www.geekmind.net/2009/11/android-simple-httpclient-to.html
Just a guess but can you try setting:
conn.setDoOutput(false);
The documentation says: "Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body." HttpURLConnection
Since you do not have anything in your body, might as well set it to false.
The documentation Android has for setRequestMethod is minimal, however your error states that POST is not a valid method. Try using PUT instead:
conn.setRequestMethod("PUT");
Also see this post for any tweaks you may need to make.

Categories

Resources