I am making a Json request and I get the data and place it in a list view but some of the strings i get have accents or 'ç' and it doesn't appear correctly.
For example, the string is 'Bragança' and i receive 'Bragança' or 'à' and get 'Ã'. If i do the request in the browser, all works properly.
My request.
public void makeJsonArrayRequest() {
RequestQueue queue = AppController.getInstance().getRequestQueue();
queue.start();
JsonArrayRequest Req = new JsonArrayRequest(urlJsonObjUtilizadas,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject ementaObj = response.getJSONObject(i);
Ementa ementa = new Ementa();
ementa.setCantina(ementaObj.getString("cantina"));
ementa.setDescricao(ementaObj.getString("descricao"));
ementa.setEmenta(ementaObj.getString("ementa"));
ementa.setPreco(ementaObj.getInt("preco"));
ementaItems.add(ementa);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
//**
// Passing some request headers
//*
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
}
};
// Add the request to the RequestQueue.
AppController.getInstance().addToRequestQueue(Req);
}
I think this is because of the wrong content type encoding header. You are supposed to use UTF-8 as encoding. Maybe this is working in the browsers because the headers are not case-sensitive (unlike Android).
Take a look here for a solution. Essentially they are manually overriding the charset.
please try to use this code for sending and receiving JSON with utf-8 encoding:
try {
URL url = new URL("your url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream(), "UTF-8");
String request = "your json";
writer.write(request);
writer.flush();
System.out.println("Code:" + conn.getResponseCode());
System.out.println("mess:" + conn.getResponseMessage());
String response = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
response += line;
}
System.out.println(new String(response.getBytes(), "UTF8"));
writer.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should add the request header charset to UTF-8. For example if your request will be as json, you should add this header to the request:
"Content-type": "Aplicación/json; utf-8"
I use Volley too and this way works for me.
Regards.
Check this sample, this way i am using, look the header section
public class Estratek_JSONString extends JsonRequest<String>{
Activity Act;
Priority priority;
public Estratek_JSONString(int m, String url, JSONObject params,
Listener<String> listener, ErrorListener errorListener,Activity act, Priority p) {
super(m,url,params.toString(),listener,errorListener);
this.Act=act;
this.priority=p;
}
public Estratek_JSONString(int m, String url,
Listener<String> listener, ErrorListener errorListener,Activity act, Priority p) {
// super constructor
//super(m,url,params.toString(),listener,errorListener);
super(m,url,null,listener,errorListener);
this.Act=act;
this.priority=p;
}
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Bearer "+Tools.Get_string(Act.getApplicationContext(),Global_vars.Access_token));
return headers;
}
//it make posible send parameters into the body.
#Override
public Priority getPriority(){
return priority;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new String(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
}
Related
I've been searching this site and others for solutions on making a POST request with a JSON body, but the solutions I've found don't seem to work for me. For reference, here is a successful request I've made using curl from the terminal:
curl -I -X POST -H "x-app-id:myID" -H "x-app-key:myKey"
-H "Content-Type:application/json" -H "x-remote-user-id:0"
https://trackapi.nutritionix.com/v2/natural/exercise -d '{
$+ "query":"ran 3 miles",
$+ "gender":"female",
$+ "weight_kg":72.5,
$+ "height_cm":167.64,
$+ "age":30
$+ }'
My attempts to convert this for an android app led me to volley, and searching around led me to use the following snippet:
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject jsonBody = new JSONObject();
jsonBody.put("query", "ran 3 miles");
jsonBody.put("gender", "female");
jsonBody.put("weight_kg", 72.5);
jsonBody.put("height_cm", 167.64);
jsonBody.put("age", 30);
final String mRequestBody = jsonBody.toString();
String url = "https://trackapi.nutritionix.com/v2/natural/exercise";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_RESPONSE", error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("x-app-id", "myID");
params.put("x-app-key", "myKey");
params.put("Content-Type", "application/json");
params.put("x-remote-user-id", "0");
return params;
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
The API dictates that the data must be sent in the body, which is why I've excluded the getParams function. This snippet seems to work for everybody else on the internet, but I consistently get 400 messages from it. I've also converted the same curl request into a request in postman, and it works great there as well. Does anyone have any insight as to where I went wrong?
EDIT: Here's a link to the api as requested
Are you sure you are passing correct id in x-app-idand other fields? Because as per the logs, it says "x-app-id" = "myId"
You need to pass the actual id of your application.
Also,
You have already defined the content-type inside getBodyContentType() so don't mention it in getHeaders() or do the opposite.
And as per API documentation , x-remote-user-id isn't required. Maybe this is the reason why your request returned an error of 400
I use this method to send out requests.
You would use this method like this.
executePost("https://trackapi.nutritionix.com/v2/natural/exercise", mRequestBody, API_KEY);
Note, for me, as you will see, I have different API keys for a prod env or lower env. So you may not need API_KEY section... but looking at your headers, you will.. :)
public static String executePost(String targetURL, String requestJSON, String apikey) {
HttpURLConnection connection = null;
InputStream is = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//TODO may be prod or preprod api key
if (apikey.equals(Constants.APIKEY_PREPROD)) {
connection.setRequestProperty("Authorization", Constants.APIKEY_PREPROD);
}
if (apikey.equals(Constants.APIKEY_PROD)){
connection.setRequestProperty("Authorization", Constants.APIKEY_PROD);
}
connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(requestJSON);
wr.close();
//Get Response
try {
is = connection.getInputStream();
} catch (IOException ioe) {
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) connection;
int statusCode = httpConn.getResponseCode();
if (statusCode != 200) {
is = httpConn.getErrorStream();
}
}
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
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();
}
}
}
I also want to make something else clear. This code is used on my local machine, it is not customer facing. The security of the code was not and is not an issue for my use case. Make sure you security store your API keys.
I'm testing the inter media API and I am trying it using this code below. I used volley for this:
String url = "https://api.infermedica.com/v2/diagnosis";
JSONArray evidence = new JSONArray();
JSONObject evidence1 = new JSONObject();
try {
evidence1.put("id", "s_1193");
evidence1.put("choice_id", "present");
} catch (JSONException e) {
e.printStackTrace();
}
try {
evidence.put(0,evidence1);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject postparams = new JSONObject();
try {
postparams.put("sex", "male");
postparams.put("age", 30);
postparams.put("evidence", evidence);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("DATA:", postparams.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(Object response) {
Log.e("DATA: ", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// As of f605da3 the following should work
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Log.e("DATA:" , obj.toString());
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("app-id", "MY-APP-ID");
headers.put("app-key", "MY-APP-KEY");
headers.put("authorization", "Basic Og==");
headers.put("Content-type", "application/json");
return headers;
}
};
Log.e("DATA: " , "calling volley");
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjReq);
After running it and checking the logs here is the result:
E/DATA:: {"sex":"male","age":30,"evidence":
[{"id":"s_1193","choice_id":"present"}]}
E/DATA:: calling volley
E/Volley: [236] BasicNetwork.performRequest: Unexpected response code 400
for https://api.infermedica.com/v2/diagnosis
E/DATA:: {"message":"bad request"}
I tried the logged json in Postman and it was accepted:
Here is the screenshot of my postman result
I've been looking for answers around here, I already added the content-type, and I made sure that my keys are correct. Am I using the volley correctly. Your help will be much appreciated.
How to send sms using Twillio Api in Android.
Here is my code.
What I don't know is how to set http request body.
When I test it using CocoaRestClient(a tool for api test), it is working well.
Help me please.
public void sendInviteSMS(String kToNumber) {
int random4Num = generateRequestCode();
...
String kTwilioSID = "...";
String kTwilioSecret = "...";
String kFromNumber = "...";
String message = String.format("%s has sent you a invite. To accept, enter the following code: %d.", AppUtil.sharedObject().userFirstName, random4Num);
String kMessage = message;
String urlString = String.format("https://%s:%s#api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID);
HashMap postData = new HashMap();
postData.put("From", kFromNumber);
postData.put("To", kToNumber);
postData.put("Body", kMessage);
// Validate user with the POST call
AsyncTask doPost = new TwilioPost(urlString) {
#Override
protected void onPostExecute(String result) {
Log.v("PHONE", result);
}
}.execute(postData);
}
...
public class TwilioPost extends AsyncTask<HashMap<String, String>, Void, String> {
private String remoteURL;
private static final String TAG = "Wayjer";
public TwilioPost(String remoteURL) {
this.remoteURL = remoteURL;
}
////////////////////////////////////////////
// Call "doPost" in the background thread
///////////////////////////////////////////
#Override
protected String doInBackground(HashMap<String, String>... hashMaps) {
try {
return doPost(hashMaps[0]);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
///////////////////////////////////////////////////////
// Override to convert result string to a JSONObject
//////////////////////////////////////////////////////
#Override
protected void onPostExecute(String result) {
try {
Log.v(TAG, result);
} catch (Exception e) {
Log.v(TAG, e.toString());
}
}
public String doPost(HashMap<String, String> postData) throws IOException {
URL url = new URL(remoteURL);
String response = "";
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
String postString = buildString(postData);
byte[] postBytes = postString.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
// Write parameter...
OutputStream outStream = connection.getOutputStream();
outStream.write(postBytes);
outStream.flush();
outStream.close();
connection.connect();
int resCode = connection.getResponseCode();
Log.v(TAG, "Response Message: " + connection.getResponseMessage());
if (resCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
response += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String buildString(HashMap<String, String> postData) throws UnsupportedEncodingException {
StringBuilder strBuilder = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : postData.entrySet()) {
try {
Log.v(TAG, "HTTPPOST ENTRY: " + entry.getKey() + " - " + entry.getValue());
if (first)
first = false;
else
strBuilder.append("&");
strBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
strBuilder.append("=");
strBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (Exception e) {
}
}
return strBuilder.toString();
}
}
Megan from Twilio here.
Interacting with the Twilio REST API directly from your mobile app is not recommended.
When sending SMS from Android, I would suggest that you have a server component using your language of choice. This allows you to keep your API credentials a secret.
Your mobile app would then connect to your server to make the request for sending SMS via the REST API with the parameters of the From, To and Body of the message:
https://www.twilio.com/docs/api/rest/sending-messages
In Java:
// You may want to be more specific in your imports
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
public class TwilioTest {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "YOUR_ACCOUNT_SID";
public static final String AUTH_TOKEN = "[AuthToken]";
public static void main(String[]args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build the parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("To", "+16518675309"));
params.add(new BasicNameValuePair("From", "+14158141829"));
params.add(new BasicNameValuePair("Body", "Hey Jenny! Good luck on the bar exam!"));
params.add(new BasicNameValuePair("MediaUrl", "http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
Please let me know if this helps!
If you can otherwise provide an example error message you may be receiving with your code, I can take a closer look.
I can't seem to get my PHP page to display the data I have sent using a http client in Android. All I need now is displaying it in PHP which seems to be a challenge, I know I have done something wrong.
Any guidance would be much appreciated. I have tried everything from var_dump($_SERVER) to json_decode to display it in PHP. Is it even possible to display it on a PHP page?
private class Connection extends AsyncTask{
#Override
protected Object doInBackground(Object[] objects){
try{
PostData(R.id.fullscreen_content, 3);
}
catch(IOException exception){
exception.printStackTrace();
}
return null;
}
}
protected void PostData(Integer Question_ID,Integer ResponseChosen_ID) {
URL url = new URL("http://10.0.2.2:443/SwlLogin.php");
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
HttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet(conn.getURL().toString());
post.setHeader("Content-type","application/json");
conn.connect();
Date date = new Date();
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd", Locale.UK);
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss",Locale.UK);
String nowDate = dt.format(date);
String nowTime = time.format(date);
String phpDate = nowDate;
String phpTime = nowTime;
ArrayList<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("Question ID", Question_ID.toString()));
params.add(new BasicNameValuePair("Response_Chosen_ID", ResponseChosen_ID.toString()));
params.add(new BasicNameValuePair("TimestampDate", phpDate));
params.add(new BasicNameValuePair("time", phpTime));
JSONArray array = new JSONArray();
array.put(params);
post.setHeader("postData", params.toString());
post.getParams().setParameter("JSON", params);
HttpParams var = httpClient.getParams();
var.setParameter("GET",params);
HttpResponse response = httpClient.execute(post);
OutputStreamWriter write = new OutputStreamWriter(conn.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
builder.append(line);
}
Log.d("Response:", builder.toString());
builder.toString();
reader.close();
public void happy_click(View view) throws IOException {
try{
new Connection().execute();
report_success();
}
catch(Exception exception){
messageBox("Response was not successful","Failed to process response" + exception.getMessage());
}
}
you can not run this code on the UI thread or you will get a NetworkRequestOnUIThread exception. you have to do this on a different thread.
try using AsyncTask via
private class Uploader extends AsyncTask<Void,Void,Void>{
protected void doInBackground(){
// do network request here
}
private void onPostExecute(){
// handle UI updates here as is on ui Thread
}
}
or you could look at using OkHTTP library which I recommend highly. to do this download the jar from okHttp. add it to you libs folder then you can do network call like this
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
JSONObject parcel = new JSONObject();
try{
parcel.put("email", emailEdit.getText().toString());
parcel.put("password", passwordEdit.getText().toString());
parcel.put("device", "Android");
parcel.put("hash", "1234");;
}catch (JSONException e ){
e.printStackTrace();
}
RequestBody body = RequestBody.create(JSON, parcel.toString());
Request request = new Request.Builder()
.header("Content-Type", "application/json")
.url("YOURURL")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if (null != e) {e.printStackTrace();}
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (null != response && response.message().equals(Constants.KEY_OK)) {
JSONObject serverResponse;
try{
serverResponse = new JSONObject(response.body().string());
if(serverResponse.getBoolean(Constants.KEY_SUCCESS)){
Constants.getInstance().setToken(serverResponse.getString(Constants.KEY_TOKEN));
moveToHomePage();
}else{
showLoginFail();
}
}catch (JSONException e ){
e.printStackTrace();
}
response.body().close();
} else {
showLoginFail();
}
}
});
also make sure you have
<uses-permission android:name="...permision.INTERNET">
in your manifest file
Guys can you help me a little bit, Im getting this error:
"JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject"
When I'm parsing the data here is my code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Here is the code where I'm instantiating the Parser:
private void fillSpinnerCabTypes() {
List<String> cabTypesSpinner = new ArrayList<String>();
JSONParser jsonParser = new JSONParser();
JSONObject cabTypesObject = jsonParser.getJSONFromUrl(urlTypeCabs);
try{
TypesArray = cabTypesObject.getJSONArray(TAG_TYPES);
for(int i = 0; i < TypesArray.length(); i++){
JSONObject c = TypesArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
cabTypesSpinner.add(name);
}
}catch(Exception e ){
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cabTypesSpinner);
final Spinner spnCabTypes = (Spinner)findViewById(R.id.spnTypeOfCab);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spnCabTypes.setAdapter(adapter);
}
I'm really stuck with this. I'm populating the spinner from a database in a backend on Django in the server.
This is my JSON data
{"Types": [{"name": "Normal"}, {"name": "Discapacitados"}, {"name": "Buseta"}]}
This issue comes from the server.
The URL you're requesting, send you back data but not in the JSON format.
The Exception you get is telling you that the String the server send you back starts with:
<!DOCTYPE
This can be:
A simple webpage (instead of raw JSON). It correspond to the first XML tag of a web page (source)
An error page generated by the server, and printed in HTML
To debug this further, simply print the content of your json variable in the logcat:
Log.d("Debug", json.toString());
jObj = new JSONObject(json);
This problem came in my code also.and solution was different.It occured due to spelling mistake of webservice.
Solution 1:
for example real the url is
http://example.com/directory/file.php
and i had used
http://example.com/directory/file1.php
Solution 2:
use loopj library .it exactly gives you the explained error.
AsyncHttpClient client = new AsyncHttpClient();
client.post(str , localRequestParams, new AsyncHttpResponseHandler() {
#Override
public void onFinish() {
super.onFinish();
Log.i("onFinish","onFinish");
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.i("onSuccess","onSuccess");
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.i("onFailure","onFailure");
}
});