I am creating a Http request to access OData services. I am getting the response but I don't know how to parse the response into a String objects so that I can add them to a ArrayList.
Here is my code:
protected List<StatusResponse> doInBackground(Void... params)
{
// TODO Auto-generated method stub
// Execute HTTP Post Request
mResponseList = new ArrayList<StatusResponse>();
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(myOdataQueryUrl);
try
{
HttpResponse responsenext = httpclient.execute(httpget);
HttpEntity entitynext = responsenext.getEntity();
AddedResult= EntityUtils.toString(entitynext);
jsonArray = new JSONArray(AddedResult);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject menuObject = jsonArray.getJSONObject(i);
String createdBy = menuObject.getString("CreatedBy");
String comment = menuObject.getString("Comment");
String location = menuObject.getString("Location");
String slot = menuObject.getString("Slot");
String reachingAt = menuObject.getString("StartTime");
String lunch = menuObject.getString("Lunch");
mResponseList.add(new StatusResponse(createdBy, comment, location, slot, reachingAt, lunch));
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mResponseList;
}
I get this response:--
{
"odata.metadata":"mysite/odata/$metadata#OStatus","value":[
{
"StatusId":2151,"Location":"Office","Slot":"Running late","StartTime":"2014-09-29T12:30:00","Comment":"-","Lunch":null,"CreatedBy":"","ModifiedBy":null,"Created":"2014-09-29T04:39:10.443","Modified":null
}
]
}
I get the following error if I try to parse it like above:
Value {"value":[{"Created":"2014-09-29T04:39:10.443","Modified":null,"StatusId":2151,"ModifiedBy":null,"Slot":"Running late","CreatedBy":"","Comment":"-","Location":"Office","Lunch":null,"StartTime":"2014-09-29T12:30:00"}],"odata.metadata":"https:\/\/mySite\/odata\/$metadata#OStatus"} of type org.json.JSONObject cannot be converted to JSONArray
You're trying to convert a normal JSON object into a JSON Array.
It also seems that you're declaring that array to be a field in stead of a local variable to your method. Are you sure that is what you need?
Related
I am working on an application in that i have developed ios code for making a webservice call and it is giving me response successfully,The same webservice call when i am trying to call in android it is not working it is not giving me response,I am posting my both code,Can anybody help me to figure it?
ios code
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#",k_SERVER_BASE_ADDRESS,service_name]];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
[request setValue:[NSString stringWithFormat:#"%#",k_CONTENT_TYPE] forHTTPHeaderField:#"Content-Type"];
// 3
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[NSString stringWithFormat:#"%#",k_USER_NAME] forKey:#"APIUserName"];
[dictionary setObject:[NSString stringWithFormat:#"%#",k_PASSWORD] forKey:#"Password"];
NSLog(#"%#",dictionary);
NSError *error = nil;
NSData *data_prm = [NSJSONSerialization dataWithJSONObject:dictionary
options:kNilOptions error:&error];
NSLog(#"%#",[[NSString alloc] initWithData:data_prm encoding:NSUTF8StringEncoding]);
if (!error) {
// 4
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data_prm completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here..
NSLog(#"this is data : %#",data);
Android Code
public class GETCONTESTANTS extends AsyncTask<Void, Void, Void> {
StringEntity se;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(StartActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
// stateList.clear();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants");
String json = "";
try {
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("APIUserName", "AFBK8#DL4EJMd6");
jsonObject.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
se = new StringEntity(json);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
In above codes "iOS code" is working fine and "android code" is not working. Can anyone please help me?
try this snippet of code may be helpful
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
String url="http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants";
public JSONParser(){
}
public JSONObject makeHttpRequest(String url){
JSONObject jo = null;
jo = new JSONObject();
try {
jo.accumulate("APIUserName", "AFBK8#DL4EJMd6");
jo.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject job=new JSONObject();
try {
job.accumulate("aloha", jo);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Log.e("url", job.toString());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url);
try {
httppost.setEntity(new StringEntity(job.toString(), "UTF- 8"));
// httppost.toString();
// Log.e("url", httppost.toString());
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
Log.e("url", json);
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jobj;
}
The following android application code in Java outputs to:
[{"handle":"DmitriyH","firstName":"Dmitriy","lastName":"Khodyrev","country":"Russia","city":"Moscow","organization":"KL","contribution":122,"rank":"master","rating":2040,"maxRank":"international master","maxRating":2072,"lastOnlineTimeSeconds":1432130513,"registrationTimeSeconds":1268570311}]}
when extracting data from codeforces api- http://codeforces.com/api/user.info?handles=DmitriyH;
but I only want "firstName" of the user.
Can anyone recommend changes to my code??
public class Http extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = http://codeforces.com/api/user.info?handles=;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView)findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("result");
}
public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
//httpStuff.setText("xxx");
int status = r.getStatusLine().getStatusCode();
if(status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data);
return last;
}
else {
Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask <String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = lastSub("avm12");
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
//httpStuff.setText("xxx");
int status = r.getStatusLine().getStatusCode();
if(status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data).getJSONArray("result").getJSONObject(0);
return last;
}
else {
Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
EDIT
Now suppose I am using the url "codeforces.com/api/user.status?handle=avm12"; and I want to extract the first ten( or say n number of them) "problem" tags. What should I do then?
Well first get the root JSONArray
JSONArray array= new JSONObject(data).getJSONArray("result");
Then in a for loop get all the needed JSONObjects
for(int k=0;k<n;k++){ // n must be less than array.length()
JSONObject problemObject=array.getJSONObject(k).getJSONObject("problem");
//do what you need to do with the problemObject E.G. Add them to an ArryList...
}
Consider adding &count=N to your url to limit the output to the needed N results...
Your first tag is a JSONArray so you need to make a method with return JSONArray instead of JSONObject. As your requirement you can get it through
jArray.getJSONObject(0).get("firstName");
Your complete JSONObject contains an array with the tag "result", so you should extract the firstName like this:
JSONArray result = json.getJSONArray("result");
JSONObject jo = result.getJSONObject(0);
String firstName = jo.getString("firstName");
In the code you posted your not using the correct URL.
The following works:
final static String URL = http://codeforces.com/api/user.info?handles=;
...
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = lastSub("DmitriyH");
final JSONArray result = json.getJSONArray("result");
final JSONObject jsonObject = result.getJSONObject(0);
return jsonObject.getString("firstName");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
....
I need to consume a json webservice method which accepts stringified jsonObject as a parameter,
This is how i am making JSONObject
btnRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
jsonObjSend = new JSONObject();
try{
jsonObjSend.put("FirstName", firstname.getText().toString());
jsonObjSend.put("LastName", lastname.getText().toString());
jsonObjSend.put("EmaillId", emailid.getText().toString());
jsonObjSend.put("Password", password.getText().toString());
jsonObjSend.put("MobileNumber", mobilenumber.getText().toString());
// jsonObjSend.put("Login_RememberMe", "true");
// JSONObject header = new JSONObject();
// header.put("deviceType","Android"); // Device type
// header.put("deviceVersion","2.0"); // Device OS version
// header.put("language", "es-es"); // Language of the Android client
// jsonObjSend.put("header", header);
}catch (JSONException e) {
e.printStackTrace();
}
new sendjsonObect().execute(URL);
}
});
}
public class sendjsonObect extends AsyncTask {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String jsonObjRecv = HttpClient.SendHttpPost(params[0],jsonObjSend);
Log.d("jsonObjSend",""+jsonObjSend);
Log.d("JsonObjRecv",""+jsonObjRecv);
return jsonObjRecv.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(Registration.this, result,Toast.LENGTH_LONG ).show();
Log.d("Result", ""+result);
}
}
This is the method where i am making the request call
public static String SendHttpPost(String URL, JSONObject jsonData) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se=null;
try {
se = new StringEntity(jsonData.toString(),HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
se.setContentType("application/json");
se.setContentEncoding("UTF-8");
// Set HTTP parameters
httpPostRequest.setEntity(se);
Log.d("Test", ""+se);
// httpPostRequest.setHeader("Accept", "application/json");
// httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
// JSONObject jsonObjRecv = new JSONObject(resultString);
//// Raw DEBUG output of our received JSON object:
// Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return resultString;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
}
return null;
}
The JSONObject received at service side is showing as null.
What is the mistake i am doing?.
did you try application/x-www-form-urlencoded as content type.
httpPostRequest.addHeader("content-type", "application/x-www-form-urlencoded");
I'm creating a android game that integrates with facebook to retrieve their photo and first name and other information using the graph, I've found out how to retrieve their photo using the below code which works perfectly but I'm struggling to find working examples of extracting other information like first_name etc...
The code I'm using to retrieve the photo and display it in a ImageView is below.
public void showPhoto(View v) {
try {
ImageView MyProfilePicImageView = (ImageView)findViewById(R.id.temp);
URL MyProfilePicURL = new URL("https://graph.facebook.com/me/picture?type=normal&method=GET&access_token="+ access_token );
Bitmap MyprofPicBitMap = null;
try {
MyprofPicBitMap = BitmapFactory.decodeStream(MyProfilePicURL.openConnection().getInputStream());
MyProfilePicImageView.setImageBitmap(MyprofPicBitMap);
}
catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
I've searched high and low but can't seem to find information on how to retrieve the other information using the graph, other information meaning first_name etc... including here on the facebook developer website (https://developers.facebook.com/docs/reference/api/) but can't find a working example.
Can anybody show me a working example to retrieve the first_name of the user so I can display it in a textview?
using this url"https://graph.facebook.com/me/friends?access_token="+accessToken you can get your friends which contains thier names and ids to get info about any of them just use `"https://graph.facebook.com/"+yourFriendId+"?access_token="+accessToken'
this will return json that you can parse and useExample
HttpClient httpclient = new DefaultHttpClient();
String url = "https://graph.facebook.com/me/friends?access_token=" + URLEncoder.encode(token);
HttpGet httppost = new HttpGet(url);
try {
HttpResponse response = httpclient.execute(httppost);
// to get the response string
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
// used to construct the string
String res = "";
for (String line = null; (line = reader.readLine()) != null;) {
res += line + "\n";
}
// here we will parse the response
JSONObject obj = new JSONObject(new JSONTokener(res));
JSONArray data = obj.getJSONArray("data");
int len = data.length();
for (int i = 0; i < len; i++) {
JSONObject currentResult = data.getJSONObject(i);
String name = currentResult.getString("name");
String icon = currentResult.getString("id");
// do what ever you want
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you change your request URL to just /me (i.e. https://graph.facebook.com/me?type=normal&method=GET&access_token=...) you'll get all available profile information for the currently authenticated user.
This JSON object should have first_name and last_name, among other attributes foud here.
Check out this handy API explorer tool to play around with what you should be seeing.
I'm having trouble doing a for each loop in my java code. I can get single json results, but how do I use a for each loop in this code?
Can someone help me?
public JSONObject feedTimeline(String username) throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = response.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
for (int i = 0; i < timeline.length(); i++) {
JSONObject value= timeline.getJSONObject(i); //no error if this i is 0 and without for each loop
return value; //getting errors because of this return tweets
}
}else{
Toast.makeText(Feed.this,"error",Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = feedTimeline("name");
return json.getString(params[0]); //this would need to change I assume?
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I'm getting an error for JSONObject feedTimeline... if I have the for loop. but if I take that for loop out, and instead of having that i in JSONObject value = timeline.getJSONObject(i) and having a numberical value like 0 or 1, then it does output.
Also, I believe in class Read, return json.getString(params[0]) would also need to be worked in as for loop? I'm just really new to JAVA and I'm trying to learn everything on my own.
Thank you in advance!
public JSONObject feedTimeline(String username) throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = response.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
for (int i = 0; i < timeline.length(); i++) {
JSONObject value= timeline.getJSONObject(i); //no error if this i is 0 and without for each loop
return value; //getting errors because of this return tweets
}
}else{
Toast.makeText(Feed.this,"error",Toast.LENGTH_SHORT);
}
// changed the position of return statement. This should work now.
return null;
}