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;
}
Related
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?
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 trying to get a cURL request work in android using the httpclient.
curl -k -X POST \
-F 'image=#00001_1.png;type=image/png' \
-F 'svgz=#00001_1.png;type=image/svg+xml' \
-F 'json={
"text" : "Hello world!",
"tid" : "0010",
"timestamp" : "1342683312",
"location" : [ 22793, -553.3344],
"facebook" :
{
"id": "4444444",
"access_token": "7FUinHfxsCTrx",
"expiration_date": "1358204400"
}
};type=application/json' \
https://example.com/api/posts
This is the code that's giving me a BAD REQUEST ERROR (400) from SERVER.
public static void example() {
HttpClient client = getNewHttpClient();
HttpPost httpost = new HttpPost("https://example.com/api/posts");
httpost.addHeader("image", "#00001_1.png; type=image/png");
httpost.addHeader("svgz", "#00001_1.png; type=image/svg+xml");
httpost.addHeader("type", "multipart/form-data");
// httpost.setHeader("Content-type", "multipart/form-data");
JSONObject data = new JSONObject();
JSONObject facebook = new JSONObject();
JSONArray location = new JSONArray();
HttpResponse response = null;
try {
data.put("text","Hello world!");
data.put("templateid","0010");
data.put("timestamp","2012-07-08 09:00:45.312195368+00:00");
location.put(37.7793);
location.put(-122.4192);
data.put("location", location);
facebook.put("id", "4444444");
facebook.put("access_token", "7FUinHfxsCTrx");
facebook.put("expiration_date", "1358204400");
data.put("facebook", facebook);
System.out.println(" ---- data ----- "+data);
StringEntity stringEntity = new StringEntity(data.toString(), "utf-8");
httpost.setEntity(stringEntity);
try {
response = client.execute(httpost);
System.out.println(" --- response --- "+response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if(entity != null) {
// A Simple Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
System.out.println(" ---- result ---- "+result);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
It works perfect from the command line, don't where I'm going wrong. Any help highly appreciated.
Also let me know if I can do it without using any library written in C (Libcurl, etc).
Thanks.
You have used stringEntity to post data. Try using UrlEncodedFormEntity to send data. Here one example how to do:
try {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("loginId", username.toString()));
nvps.add(new BasicNameValuePair("password", password.toString()));
nvps.add(new BasicNameValuePair("_eventId_submit", "Submit"));
HttpPost httppost = new HttpPost("url2");
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpParams params = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(params, 45000);
HttpConnectionParams.setSoTimeout(params, 45000);
// Perform the HTTP POST request
HttpResponse response = client.execute(httppost);
status = response.getStatusLine().toString();
if (!status.contains("OK")) {
throw new HttpException(status);
}
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
cookie = cookies.get(i);
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException 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();
}
Just want to check whether this JSON Parser with async task is it correctly done? When I put this code into my Eclipse, this (method.equals("POST") was underline red. And it state that the 'method' cannot be solved. Any suggestion or help in this? Thank you.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String url=null;
List<NameValuePair> nvp=null;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
BackGroundTask Task= new BackGroundTask(url, method, params);
try {
return Task.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} 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());
}
// 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;
}
}
}
You forgot to declare method property in your BackGroundTask class.
EDIT Like this:
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
String method = null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
this.method = method;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} 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());
}
// 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;
}
}
}
You need to set method as a class variable within BackGroundTask. You are passing it into the constructor but not going anything with it. Set it the same way you have done with url and postparams.
I am not able to retrieve the data from the server. I am not sure where i have gone wrong in the code..When i run the application, the data from the server is not displayed on the emulator.. The code is given below
private void postData1(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxxxx.co.uk/NottTest/post.php");
JSONObject json = new JSONObject();
try {
// JSON data:
try {
json.put("name", "Fahmi Rahman");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
json.put("position", "sysdev");
JSONArray postjson = new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost", postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
tv.setText("Hiii");
// for JSON:
if (response != null)
{
Log.i("Json","respose");
System.out.print("loooooooooool");
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
else{
tv.setText("no respose");
Log.i("Noting","happended");
}
//tv.setText(text);
} catch (ClientProtocolException e) {
Log.i("Error","Prtocol");
} catch (IOException e) {
Log.i("Error","IO");
} catch (JSONException e) {
Log.i("Error","JOSON");
}
}
i think the error is in
try {
json.put("name", "Fahmi Rahman");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
json.put("position", "sysdev");
JSONArray postjson = new JSONArray();