I want to send data as a string to an api from android app, but when I send large amount of data in string form it shows me this error "java.net.ProtocolException: content-length promised 16280 bytes, but received 16272" . And if I send small amount of data it don't give any error. Its saying something about content length mismatch and I am not getting it.
I am sharing you my code please check
enter code here
private class AsyncTaskRunner extends AsyncTask<Void,
Void, ArrayList<String[]>> {
private String resp;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(true);
progressBar.setMessage("Fetching Contacts ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
}
#Override
protected ArrayList<String[]> doInBackground(Void... params) {
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
// ArrayList<String[]> contacts = new ArrayList<String[]>();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id =cur.getString(cur.getColumnIndex
(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex
(ContactsContract.Contacts.DISPLAY_NAME));
String phones = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex
(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
if (Integer.parseInt(cur.getString(cur.getColumnIndex
(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.
CONTENT_URI,null,
ContactsContract.CommonDataKinds.
Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
// Do something with phones
phones = pCur.getString(pCur.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
// String[] str = new String[3];
// str[0] = id;
// str[1] = name;
// str[2] = phones;
// contacts.add(str);
}
pCur.close();
}
}
String[] str = new String[3];
str[0] = id;
str[1] = name;
str[2] = phones;
long val1 = adapter1.insertContacts(id, name, phones);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name);
jsonObject.put("phones", phones);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("value is", "" + val1);
contacts.add(str);
}
}
cur.close();
String name = "Siddhant";
String postjson = String.valueOf(jsonArray);
rsp = serviceResponse(postjson, Config.URL_SAVE_CONTACTS);
Collections.sort(contacts, ALPHABETICAL_ORDER);
mAllData.addAll(contacts);
return contacts;
}
private Comparator<String[]> ALPHABETICAL_ORDER =
new Comparator<String[]>()
{
#Override
public int compare(String[] lhs, String[] rhs) {
int res = String.CASE_INSENSITIVE_ORDER.compare(lhs[1], rhs[1]);
if (res == 0) {
res = lhs[1].compareTo(rhs[1]);
}
return res;
}
};
#Override
protected void onPostExecute(ArrayList<String[]> result) {
super.onPostExecute(result);
adapter = new ContactsListAdapter(getActivity(), contacts);
listView.setAdapter(adapter);
progressBar.dismiss();
if (rsp!=null) {
String json = rsp.toString();
Toast.makeText(getActivity(), json, Toast.LENGTH_SHORT).show();
}
}
}
public String serviceResponse(String postStr, String urlString) {
HttpURLConnection connection = null;
try {
// original code
// Create connection
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www- form-urlencoded");
// connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty
("Content-Length", "" +Integer.toString(postStr.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(false);
// Send request
DataOutputStream wr =
new DataOutputStream(connection.getOutputStream());
wr.writeBytes(postStr);
wr.flush();
wr.close();
int status = connection.getResponseCode();
// return String.valueOf(status);
InputStream is;
if (status >= HttpStatus.SC_BAD_REQUEST)
is = connection.getErrorStream();
else
is = connection.getInputStream();
// Get Response
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
return response.toString();
} catch (Exception e) {
e.getMessage();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
I think it is about getBytes()
Be careful when you use it because you have to pass the character encoding parameter like .getBytes("UTF-8")
If you don't pass any parameter it will use the system default.
My educated guess is that your data is not a standard UTF-8 data so you should give the correct character set and i think after that your data length will match.
Edit:
Now, I see your mistake.
When you set
wr.writeBytes(postStr);
It sets the encoding wrongly again :)
You should do something like that:
wr.write(postStr.getBytes("UTF-8"));
p.s: you should change "UTF-8" to anything that supports your language to get your data on the server side correctly.
Related
I am trying to get a user token from a url but I keep getting an IOException:
(W/System.err: java.io.FileNotFoundException: url)
I have tried to run the API from postman, and that seems to work. The request method is GET:
private class userlogin extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
progressDialog = new ProgressDialog(userLogin.this);
progressDialog.setMessage("please wait.........");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setTitle("Logging in");
progressDialog.show();
}
#Override
public String doInBackground(String... para) {
try {
URL url = new URL(webconfigs.LOGIN_URL);
Map<String, String> params = new LinkedHashMap<>();
params.put("grant_type", "password");
params.put("username", para[0]);
params.put("password", para[1]);
utility.updateSharedPreference(userLogin.this, "Username", para[0]);
utility.updateSharedPreference(getApplicationContext(), "Password", para[1]);
//just to check if it is sored in the shared prefrence
utility.fetchFromSharedPreference(getApplicationContext(), "Username");
utility.fetchFromSharedPreference(getApplicationContext(), "Password");
Log.e(">>Username>>", para[0]);
Log.e(">>Password>>", para[1]);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
String urlparameters = postData.toString();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", webconfigs.CONTENT_TYPE);
conn.setDoOutput(true);
//connect the url
conn.connect();
//conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlparameters);
writer.flush();
//create our buffered reader to read from the input stream reader
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder st = new StringBuilder();
//checking the status of the response code
Integer resposeCode = conn.getResponseCode();
String responsecode1 = resposeCode.toString();
Log.e("the respose code is :", responsecode1);
String line;
String result= "";
// consume the response and read it line by line as
while ((line = reader.readLine()) != null) {
st.append(line);
}
reader.close();
writer.close();
result = st.toString();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(">>>>LOGINSERVERRESPONSE", ">>>>>" + result);
progressDialog.dismiss();
try {
JSONObject results = new JSONObject(result);
String token = results.getString("access_token");
if (token != null) {
String accessToken = results.getString("access_token");
String tokenType = results.getString("token_type");
String dateIssued = results.getString(".issued");
String expiryDate = results.getString(".expires_in");
}
} catch (Exception e) {
}
startActivity(new Intent(getApplicationContext(), drawerLayout.class));
}
}
the problem with using the asynchtask is that when the credentials that are used are wrong the problem will exist ,incase that happens,use a different user from the database
public class PerformNetworkTasks extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<String>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo.toString();
/*
right now I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
inputDataTV.setText(result);
}
I need to return some data individually. So I need to return an array (i think) so that I can set the TextView as e.g. arrays.get(number).
Is there some other way that I am not realizing here, or should I continue with what I am doing to get the data individually?
Just to add, I am getting the info from a website.
You can return any data type you want
but your AsyncTask structure should be based on result data type
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>/*resultParam*/> {
#Override
protected List<String>/*will same as result parma*/ doInBackground(String... params) {
return null;/*now you can return list of string*/
}
#Override
protected void onPostExecute(List<String>/*finally receive result*/ result) {
super.onPostExecute(result);
}
}
so your code will be
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>> {
#Override
protected List<String> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo;
/*
right now
I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
inputDataTV.setText(result.get(0));
}
}
So I have been trying to figure out a way to save the Access Token I get from my API. I can successfully get the JSON response from my API and store it in my result variable within my doInBackground.
However, for some reason it is not getting saved in SharedPreferences in my onPostExecute.
The result variable contains this JSON string {"access_token":"4Oq6o8oAGRf4oflu3hrbsy18qeIfG1","expires_in":36000,"token_type":"Bearer","scope":"read write","refresh_token":"iocSNJ2PTVbph2RnWmcf0Zv69PDKjw"}, which I received from my API.
I have an algorithm that is supposed to save only the access_token for now.
My code is below:
WSAdapter.java
public class WSAdapter {
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
static String MyPREFERENCES = "API Authentication";
String accessToken = "Access Token";
private WeakReference<Context> mLoginReference;
// constructor
public SendAPIRequests(Context context){
mLoginReference = new WeakReference<>(context);
}
#Override
protected String doInBackground(String... params) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
//String data = "";
StringBuilder result = new StringBuilder();
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[2]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept","application/json");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// Tells the URL that I want to read the response data
httpURLConnection.setDoInput(true);
// JSON object for the REST API
JSONObject jsonParam = new JSONObject();
jsonParam.put("client_id", "mYIHBd321Et3sgn7DqB8urnyrMDwzDeIJxd8eCCE");
jsonParam.put("client_secret", "qkFYdlvikU4kfhSMBoLNsGleS2HNVHcPqaspCDR0Wdrdex5dHyiFHPXctedNjugnoTq8Ayx7D3v1C1pHeqyPh1BjRlBTQiJYSuH6pi9EVeuyjovxacauGVeGdsBOkHI3");
jsonParam.put("username", params[0]);
jsonParam.put("password", params[1]);
jsonParam.put("grant_type", "password");
Log.i("JSON", jsonParam.toString());
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes(jsonParam.toString());
// Flushes the jsonParam to the output stream
wr.flush();
wr.close();
// // Representing the input stream
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// reading the input stream / response from the url
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", result.toString());
return result.toString();
}
#Override
protected void onPostExecute(String result) {
//super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// retrieves the context passed
Context context = mLoginReference.get();
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// edits shared preferences for authentication and authorization
PrefEditor = ShPreference.edit();
// to save the Access Token from the API
try {
JSONObject pJObject = new JSONObject(result);
PrefEditor.putString(accessToken, pJObject.getString("access_token"));
PrefEditor.apply();
// algorithm for parsing the JSONArray from the Django REST API
/*for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
PrefEditor.putString(accessToken, pJObj_data.getString("access_token"));
PrefEditor.apply();
}*/
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
This code below includes the code that reads the SharedPreferences. Which should be in the doInBackground of this AsyncTask as I need to put the access_token to the header.
This is supposed to be in the same class.
public class SendPostsRequest extends AsyncTask<String, String, String> {
TextView postsSect;
// Add a pre-execute thing
HttpURLConnection urlConnection;
// gets the activity context
private WeakReference<Context> mPostReference;
// to be able to access activity resources
Activity activity;
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
String accessToken = "Access Token";
// constructor
public SendPostsRequest(Context context, Activity activity){
mPostReference = new WeakReference<>(context);
this.activity = activity;
}
#Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
// retrieves the context passed
Context context = mPostReference.get();
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String APIAuthentication = "Bearer " + ShPreference.getString(accessToken, "");
try {
// Sets up connection to the URL (params[0] from .execute in "login")
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", APIAuthentication);
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// gets the JSON files stored in the posts details class from Posts Activity
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// retrieves the context passed
Context context = mPostReference.get();
// For posts
try {
JSONArray pJObjArray = new JSONArray(result);
// algorithm for parsing the JSONArray from the Django REST API
for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
// inputs necesarry elements to the ListPosts function
postsHelper.setPost(pJObj_data.getInt("id"), pJObj_data.getString("post_title"), pJObj_data.getString("post_content"));
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
// checks if context is not null before updating posts page
if (context != null){
postsSect = (TextView) activity.findViewById(R.id.PostsSection);
int lastFrJSONArray = postsHelper.getPostID().size() - 1;
// outputs the id of the very first post, something to put to the textview
postsSect.setText("id: " + postsHelper.getPostID().get(lastFrJSONArray - 2) + "\n");
for (int i = lastFrJSONArray; i >= 0; i--)
{
// appending the titles and contents of the current post
postsSect.append("title: " + postsHelper.getPostTitle().get(i) + "\n");
postsSect.append("content: " + postsHelper.getPostContent().get(i) + "\n");
// if this is the last post, then don't need to append id for the next post.
if (i != 0) {
postsSect.append("id: " + postsHelper.getPostID().get(i) + "\n");
}
}
}
}
}
UPDATE:
I have edited my JSON parsing algorithm.
Instead of parsing my JSON object from result as an array, this code here now parses it as an object. The JSONarray algorithm should be commented out.
The response you get from your webservice is actually not a JSONArray, but just a simple JSONObject. Hence change this line:
JSONArray pJObjArray = new JSONArray(result);
to
JSONObject pJObjArray = new JSONObject(result);
If You are not getting token just follow this code. it may help you.
//member variable
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
String ApiToken;
OnCreate(){
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
ApiToken = ShPreference.getString(accessToken, "");
// call wherever you want
new SendPostsRequest(ApiToken).execute()
}
public class SendPostsRequest extends AsyncTask<String, String, String> {
private String APIToken;
TextView postsSect;
// Add a pre-execute thing
HttpURLConnection urlConnection;
// gets the activity context
// constructor
public SendPostsRequest(String APIToken){
this.APIToken = APIToken;
}
#Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
// retrieves the context passed
Context context = mPostReference.get();
String APIAuthentication = APIToken; // or you can direct pass
try {
// Sets up connection to the URL (params[0] from .execute in "login")
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", APIAuthentication);
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// gets the JSON files stored in the posts details class from Posts Activity
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// retrieves the context passed
Context context = mPostReference.get();
// For posts
try {
JSONArray pJObjArray = new JSONArray(result);
// algorithm for parsing the JSONArray from the Django REST API
for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
// inputs necesarry elements to the ListPosts function
postsHelper.setPost(pJObj_data.getInt("id"), pJObj_data.getString("post_title"), pJObj_data.getString("post_content"));
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
// checks if context is not null before updating posts page
if (context != null){
postsSect = (TextView) activity.findViewById(R.id.PostsSection);
int lastFrJSONArray = postsHelper.getPostID().size() - 1;
// outputs the id of the very first post, something to put to the textview
postsSect.setText("id: " + postsHelper.getPostID().get(lastFrJSONArray - 2) + "\n");
for (int i = lastFrJSONArray; i >= 0; i--)
{
// appending the titles and contents of the current post
postsSect.append("title: " + postsHelper.getPostTitle().get(i) + "\n");
postsSect.append("content: " + postsHelper.getPostContent().get(i) + "\n");
// if this is the last post, then don't need to append id for the next post.
if (i != 0) {
postsSect.append("id: " + postsHelper.getPostID().get(i) + "\n");
}
}
}
}
}
I have been working on the following code for a while.
the code worked for the 5.x version of my app but I can't get the code to work for Android version 6.x and higher.
public class PostAsync extends AsyncTask<String, Integer, Double> {
private Context _context = null;
public PostAsync(Context context) {
_context = context;
}
#Override
protected Double doInBackground(String... params) {
String serverResponse = postData(params[0]);
try {
JSONObject obj = new JSONObject(serverResponse);
String id = "";
JSONObject locationobj = obj.getJSONObject("X");
JSONObject response = locationobj.getJSONObject("Y");
id = response.getString("id");
Settings.idcode = id;
// Convert , to %2c, since we're working with a URI here
String number = Settings.number + Settings.code + "," + Settings.idcode; // %2c
_context.startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel://" + number)));
}
catch (Exception e) {
// TODO: Errorhandler
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
}
protected void onProgressUpdate(Integer... progress) {
}
// Send a POST request to specified url in Settings class, with defined JSONObject message
public String postData(String msg) {
String result = null;
StringBuffer sb = new StringBuffer();
InputStream is = null;
try {
URL url = new URL(Settings.webURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setChunkedStreamingMode(0);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestProperty("Content-Encoding", "identity");
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("TYPE", "JSON");
connection.setRequestProperty("KEY", "key");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(msg);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMessage);
if(responseCode == HttpURLConnection.HTTP_OK){
is = new BufferedInputStream(connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
try {
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
I get the following error
java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK
Can someone tell me what I am missing?
Hello is have this code on Android Studio:
private class ConsultarrDatos extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("onPostExecute:::::::::::::::::::::::::: " + result);
String strJson= result;
String data = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("name").toString();
float salary = Float.parseFloat(jsonObject.optString("salary").toString());
data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
etName.setText(name);
}
} catch (JSONException e) {e.printStackTrace();}
}
}
The thing is, when I recive data from a PHP file the println is printing that:
I/System.out: onPostExecute::::::::::::::::::::::::::
04-03 18:25:50.798 18046-18046/com.example.lorenzo.phpmysql I/System.out: ���
My php code is OK, I don't have any error or things like that!
Do you know why?
Thanks a lot!
This is my downloadUrl
private String downloadUrl(String myurl) throws IOException {
Log.i("URL",""+myurl);
myurl = myurl.replace(" ","%20");
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("respuesta", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}