I have one api. In that i have to pass some parameters, some parameters among them i have to pass them like array arraylist. My example Request ?Url is as below:
http://yehki.epagestore.in/app_api/order.php?customer_id=3&address_id=31&products%5B0%5D%5BproductName%5D=rt&products%5B0%5D%5Bproduct_id%5D=41&products%5B0%5D%5Bquantity%5D=2&products%5B0%5D%5Bunit%5D=1&products%5B0%5D%5BunitPrice%5D=400
MY API request with parameters
I havej no idea how to build; this kind if request url... Can anyone suggest me for it what should i do..Or any help code?
private String httpGetRequest() throws Exception
{
String receiveStr = "";
String urlRequest = urlString;
DefaultHttpClient client = null;
HttpResponse execute;
client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urlRequest);
execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = buffer.readLine()) != null)
stringBuffer.append(line);
client.getConnectionManager().shutdown();
client = null;
receiveStr = stringBuffer.toString();
return receiveStr;
}
Then for parse JSON you can use usefull GSON library.
You must create variable urlString in code :
String urlString = "http://yehki.epagestore.in/app_api/order.php?customer_id=3&address_id=31&products%5B0%5D%5BproductName%5D=rt&products%5B0%5D%5Bproduct_id%5D=41&products%5B0%5D%5Bquantity%5D=2&products%5B0%5D%5Bunit%5D=1&products%5B0%5D%5BunitPrice%5D=400"
by your current Get Http parametrs: customer_id, address_id, etc
This code above return to you String variable like this: "{"status":"Sucess","order_id":1070,"order_product_id":[1325],"complete_order_time":["1"],"product_id":["41"],"payee_key":["2511131I093517"]}"
Then you must parse it JSON string variable. Very usefull library for parse JSON string is GSON library . Read this https://sites.google.com/site/gson/gson-user-guide
Related
I am relatively new to Android and I am using JSON to get data from a server. On the first loop at line 22, the StringBuilder contains, 500 Internal Server Error and then the jArray ends up coming back null. How can I handle this error?
public static JSONObject getJSON() {
String jsonString = "";
InputStream inStream = null;
//http post
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost(WS_URL);
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
inStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inStream.close();
jsonString = sb.toString();
jArray = new JSONObject(jsonString);
//outputTransactions(jArray);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jArray;
}
Though its a late reply but it might help others. You need to check the response status from the server before parsing it as JSON.
For ex.
int status_code=response.getStatusLine().getStatusCode();
if(status_code!=200){
Log.d("MYLOG","ERROR! Response status is"+status_code);
}
else{
inStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inStream.close();
// Rest of your code......
}
or Optionally you can check the status code and display the error to the user
Like:
else if(status_code==404){
Log.d("MYLOG","Sorry! Page not found! Check the URL ");
}else if(status_code==500){
Log.d("MYLOG","Server is not responding! Sorry try again later..");
}
Hope it helps for newbies like you :-)
A "500 Internal Server" error means the server had a problem responding to your request. You are not getting a JSON string response.
Then when you try to create your jArray, the string is not valid JSON and the JSONObject cannot parse it - it returns "null" as you say.
You can parse the server response to see if it contains this string, and then create whatever jArray object you want, but you can't get a JSON object from a non-JSON string.
Take a look at this answer: https://stackoverflow.com/a/8148785/1974614
You should check the statusCode against 500
You should consider use a library to handle the REST requests like: http://square.github.io/retrofit/
If you use a library like that you can get an object from json when a success response is available and other when an error occur.
MyApi mylogin = restAdapter.create(MyApi.class); //this is how retrofit create your api
mylogin.login(username,password,new Callback<String>() {
#Override
public void success(String s, Response response) {
//process your response if login successfull you can call Intent and launch your main activity
}
#Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace(); //to see if you have errors
}
});
}
I got the same problem like you and I solved it because I missed a part while adding GSON .jar files to adding my serverside project. I think you should carrefully add external libraries to your project too like me.With these links I could aware of problem .
LINK 1
LINK 2
i am developing an android application with RESTful WebServices
suppose ,
i am sending a url http request as somewebservice/data/access
and is sends data as {"serviceMessageCode":1,"serviceMessageText":"aaaaaa","items":null}
and i want to send another request with that obtained key as
somewebService/rest/services/secure/getcategories?apikey=aaaaaa
int sMC = jsonObj.getInt("serviceMessageCode");
if (sMC == 1) {
smt = jsonObj.getString("serviceMessageText");
can i use somewebService/rest/services/secure/getcategories?apikey=smt
i think i should not do so , some one tell me how to achieve this..!!
please help....
There is no reason why you could not pass some data by GET parameters. It really depends on Rest API on your backend server. Do you use any REST client or base apache http package classes to make requests to server?
Edited:
BufferedReader in = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
String uri = String.format("http://somewebService/rest/services/secure/getcategories?apikey=%s", Config.API_KEY); // API_KEY is constant value written somewhere or could you pass it as method argument
URI website = new URI(uri);
request.setURI(website);
HttpResponse response = httpclient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
StringBuilder builder = new StringBuilder();
while(null != (line = in.readLine())) {
builder.append(line);
}
in.close();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
I create android apps as client and node as server, i got problem when i request value from android to node, i use this code in android to communicate with node js
String xResult = getRequestJSON("http://mydomain.com:8888");
public String getRequestJSON(String Url){
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
HttpResponse response = client.execute(request);
sret =requestJSON(response);
}catch(Exception ex){
}
return sret;
}
public static String requestJSON(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
and i got result like this in node.
[{"posid":"P0S6f50b314b2c279a2083cb0ef821ccb4d20140218120720","id_a":"ltv#ltv.com","gambar_a":"6f50b314b2c279a2083cb0ef821ccb4d.jpg","user":"lutfi soe","pwaktu":"2014-02-18T05:07:20.000Z","posnya":"test dr android","plat":-7.983757710988161,"plong":112.6549243927002,"pjenis":"I","vote":0}]
my question is,how i receive json like that in android ?and parse to string?
thanks
If you are receiving Json string in proper format then you can use JSON jar to parse this json.
You can get a tutorial for JSON parsing here
I think your question is more on how to parse and access the result in java[read Android].
Here is a solution that could help JavaScript type arrays in JAVA
JsonArray yourArray = new JsonParser()
.parse("[[\"2012-14-03\", 2]]")
.getAsJsonArray();
// Access your array like so - yourArray.get(0).getAsString();
// yourArray.get(0).getAsInt() etc
The above is using a library called Gson
P.S: I just plagiarized my own answer. Not sure what criteria to use to mark this question as a duplicate
I want to send an image captured by camera to a server, which creates blob key. I am not getting how to send that image to the server. In which format is the image is sent?
I am trying to send parameters through HttpParams.
This is my code but the data is not going to server. What is the problem?
String name=tname.getText().toString();
String addr=taddr.getText().toString();
String age=tage.getText().toString();
String cnct=tcnct.getText().toString();
String gen=tgen.getText().toString();
String wtm=twtm.getText().toString();
ba1=Base64.encodeToString(imageform, 0);
Date d=new Date();
String date=d.toString();
InputStream i1;
String back="";
HttpParams p=new BasicHttpParams();
p.setParameter("vname",name);
p.setParameter("address", addr);
p.setParameter("age", age);
p.setParameter("contact", cnct);
p.setParameter("gender", gen);
p.setParameter("whomto", wtm);
p.setParameter("myFile", ba1);
try {
HttpClient httpclient = new DefaultHttpClient(p);
HttpPost res=new HttpPost(result);
HttpResponse response = httpclient.execute(res);
HttpEntity entity = response.getEntity();
i1 = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(i1,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
if ( reader.readLine() == null) {
Log.e("inside if","No data");
} else {
String line = reader.readLine();
i1.close();
back=sb.toString();
}
I am not getting any errors or exceptions.
You should make an MultipartPost and add the file to your MultipartEntity as follows :
multipartEntity.addPart("data", new FileBody(capturedImagePath));
You should have a look a this answer Multipart post with Android for a more detailed answer.
Encode the image, using Base64, to a String and send it using MultipartEntity.
In php retrieve the string an unpack it with base64_decode to the image.
Check this question:
https://stackoverflow.com/questions/10145417/android-send-image-through-http-post
I need to download an HTML page programmatically and then get its HTML. I am mainly concerned with the downloading of the page. If I download the page, where will I put it?
Will I have to keep in an String variable? If yes then how?
This site provides a good explanation on how to download a file, and also how to set the location to where it should be stored. You do not have to, and should not, keep it in a string variable. If you are to manipulate the data I would suggest you use an XML parser.
You can call this method in doInBackground of AsyncTask
String html = "";
String url = "ENTER URL TO DOWNLOAD";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();