I am trying to create a function to make a request, but it is giving some error, I already put permission to the internet, but still
This is my code:
public String request(String Url,JSONObject Data){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Url);
InputStream inputstream;
String content = "";
try {
httppost.setEntity(new StringEntity(Data.toString()));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
while(true){
if(entity != null){
inputstream = entity.getContent();
content = inputstream.toString();
break;
}
}
} catch (Exception ex) {
return ex.toString();
}
return content;
}
Input:
JSONObject data = new JSONObject();
data.put("teste","teste");
String response = request('urlExample',data);
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();
Output:
android.os.NetworkOnMainThreadExecption
I suggest you to use AsyncTask as I mentioned in the comment :
private class LongOperation extends AsyncTask<Void, Void, String> {
private String mUrl;
private JSONObject mData;
public LongOperation(String url, JSONObject data) {
mUrl = url;
mData = data;
}
#Override
protected String doInBackground(Void... params) {
return request(mUrl, mData);
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(getApplicationContext(),response,
Toast.LENGTH_SHORT).show();
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
You can start your AsyncTask as follow:
JSONObject data = new JSONObject();
data.put("teste","teste");
new LongOperation('urlExample', data).execute();
Network operation does not be launched on Main Thread. You can create another Thread for running it.
Thread thread = new Thread(new Runnable(){
#Override public void run(){
// Run request here !!!!
}
});
thread.start();
I recomend you to use **Volley**, it's a side client library which helps you with the Http-Request.
Search for StringRequest.
Related
i want to get data from my server with AsyncTask and then extract some and send to another location and get more info from that
for first section I'm using from this code for run my AsyncTask method and Cancel AsyncTask after some time (for no response...)
new MySecendServer(link, param,mInstagramSession).execute();
final ProgressDialog pd2 = new ProgressDialog(testActivity.this);
pd2.show();
final Timer tm = new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
count++;
if (count == 30) {
pd2.cancel();
tm.cancel();
new MySecendServer(.....) .cancel(true); }
}
});
}
}, 1, 1000);
then after get data from my server i try to get more info with this code but i don't get any response or exception i test this code in doInBackground And onPostExecute and no any diffrent and no any response
try {
String requestUrl = "https://api.instagram.com/v1/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(requestUrl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (Exception ex) {}
now anyone can give me reason or any suggest for do this work ?
thanks
Update :
I found exception here :
HttpResponse httpResponse = httpClient.execute(httpGet);
and message is :
cause NetworkOnMainThreadException (id=831620140512)
Update 2 :
My first AsyncTask
public class MySecendServerClass extends AsyncTask {
private String link="";
private String [][]pparams;
private InstagramUser IG_User;
private InstagramSession IG_Session;
public MySecendServerClass(String link,String [][]params,InstagramSession user){
this.link=link;
this.pparams=params;
this.IG_Session = user;
}
#Override
protected String doInBackground(Object... arg0) {
String data="";
try{
if(pparams!=null){
for(int i=0;i<pparams.length;i++){
if(i!=0){
data+="&";
}
data+=URLEncoder.encode(pparams[i][0],"UTF8")+"="+URLEncoder.encode(pparams[i][1],"UTF8");
}
}
URL mylink=new URL(link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line);
}
Log.d("sssss",sb.toString());
return sb.toString();
}
catch(Exception ex){
}
return null;
}
#Override
protected void onPostExecute(Object tr) {
super.onPostExecute(tr);
String result = (String)tr;
try{
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("followlist");
JSONObject jObject = jArray.getJSONObject(0);
String client_id=jObject.getString("client_id");
GrtUserProfile(client_id);
}
catch(Exception ex){
}
}
}
Solve Problem With this Code :
public void GrtUserProfile(String Cid) {
String requestUrl= "https://api.instagram.com/v1/users/"+Cid+"/"+"&access_token="+mInstagramSession.getAccessToken();
new HTTPRequestClass().execute(requestUrl);
}
class HTTPRequestClass extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
String url = urls[0];
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
return response;
} catch (Exception e) {
return "";
}
}
protected void onPostExecute(String Response) {
Log.i("Response", Response);
}
}
Instead of using Timer to cancel async task you can set timeout for HttpURLConnection
private class DownloadFilesTask extends AsyncTask<URL, Integer, Boolean> {
protected Boolean doInBackground(URL... urls) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Boolean result) {
showDialog("Downloaded " + result );
}
}
This url is executed when a button is clicked
new HttpAsyncTasks().execute("http://www.demo.com/xyz");
this is the asynctask for the above execution
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return POSTS(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "successfull!", Toast.LENGTH_LONG).show();
//call main activity activity upon successful registration
Intent callMain = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(callMain);
}
}
The doInbackground of the above never gets executed but the onPostExecute method does.
this is the POSTS method called in doInbackground
public String POSTS(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("xyz", "xyz");
jsonObject.accumulate("amount", "800");
jsonObject.accumulate("demo", "demo");
jsonObject.accumulate("demo2", demo2);
// 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
StringEntity se = new StringEntity(json);
// 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");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
Please what could be wrong?
Can you try this with way. It's checking your POSTS method.
If toast show empty line, your error in POSTS method on WebProcess.
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
private String myResult="check";
#Override
protected String doInBackground(String... urls) {
try
{
myResult = POSTS(urls[0]);
}
catch(Exception e)
{
return e;
}
return myResult;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
/* other codes */
}
}
Your POSTS(urls[0]) call must be giving an exception and when it does the rest of the code is skipped and it bypasses your toast. Try removing exception you can find it in logcat.
I am new to NoSQL database and cloud. I am trying to develop a simple application in android using Clusterpoint (DBAAS). I tried and searched so many possibilities, but it is not quite working.
(new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
String requestString = "https://username:password#api-eu" +
".clusterpoint.com/908/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(requestString);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (IOException e) {
result = "Error";
e.printStackTrace();
} finally {
Log.v("ClusterResponse", result);
return result;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.v("ClusterResponse", s);
}
}).execute();
In my code i replaced username and password with original values.
I got the connection. I am posting my code so the next person can get it right in a much faster way
My mistakes
- Needed GET instead of POST
- Authorization should be of base64 with NOWRAP , so it won't add "CR" line at the end.
(new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
String requestString = "https://api-eu.clusterpoint.com/908/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestString);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpget.addHeader("Authorization", "Basic "+Base64.encodeToString
("username:password".getBytes(),Base64.NO_WRAP));
result = httpClient.execute(httpget, responseHandler);
} catch (IOException e) {
result = e.toString();
e.printStackTrace();
} finally {
Log.v("ClusterResponse", "Done");
return result;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getBaseContext(), s, Toast.LENGTH_LONG).show();
Log.v("ClusterResponse", s);
}
}).execute();
I'm trying to POST data in JSON format to a script I have running PHP on my webserver. I have found this post: How to send data to a website using httpPost, app crashes.
Using the code he wrote (putting it on a separate thread first) I am able to post data to the PHP script, which accesses it by the $_POST variable. However, I wish to post my data in JSON format. I am guessing it would require me to post a raw stream of data to the server. What functions are available to achieve this? I would also need to post images as a stream of data to the PHP script so I think this solution will also help me in that area.
Additionally, what are the advantages of posting JSON to the server rather than using the method he used?
I am programming the client side in Java in conjunction with the Android SDK.
Any help would be appreciated.
I have a sample example for posting json data .
Have a look at this:
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private Context mContext;
private Intent mIntent;
private ProgressDialog pdLoading;
private class LoginTask extends AsyncTask<Void, Void, String>
{
private ArrayList<NameValuePair> mParams = new ArrayList<NameValuePair>();
private JSONArray mJArray = new JSONArray();
private JSONObject mJobject = new JSONObject();
private String jsonString = new String();
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.show();
}
#Override
protected String doInBackground(Void... params) {
try {
mJobject.put("userName", "test");
mJobject.put("password", "test");
mJArray.put(mJobject);
mParams.add(new BasicNameValuePair("message", mJArray.toString()));
jsonString = WebAPIRequest.postJsonData("http://putyoururlhere.com/login.php?", mParams);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return jsonString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdLoading.dismiss();
if(result!=null)
{
/* try {
mJobject = new JSONObject(jsonString);
if(mJobject.getString("Success").equals("True"))
{
mJArray = mJobject.getJSONArray("user");
JSONObject mUser = mJArray.getJSONObject(0);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Log.e(TAG, jsonString);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialization();
new LoginTask().execute();
}
private void initialization() {
mContext = this;
mIntent = new Intent();
pdLoading = new ProgressDialog(mContext);
pdLoading.setMessage("loading...");
}
}
and
public class WebAPIRequest {
public static String convertStreamToString(InputStream is)
throws IOException {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
public static String postJsonData(String url, List<NameValuePair> params) {
String response_string = new String();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
try {
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
String sampleurl = url + "" + paramString;
Log.e("Request_Url", "" + sampleurl);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
InputStream in = response.getEntity().getContent();
response_string = WebAPIRequest.convertStreamToString(in);
}
} catch (Exception e) {
e.printStackTrace();
}
return response_string;
}
}
EDIT :
try,
print_r(json_decode($_POST['message'], true);
or
$data = file_get_contents('php://input');
$json = json_decode($data,true);
I hope it will be helpful !!
I'm implementing a class which extends AsyncTask and I perform an http request within this class. The class is not an Activity and is located in a seperate java file because I want to use this class several times.
I instantiate an object of this class in my Activity, to execute the http request in a separate thread. When the thread executes, I want to call a method of my Activity.
How do I implement this? I need the result of the http request in my Activity but I can't handle this so far.
This is the code for the thread task...
public class PostRequest extends AsyncTask<String, Void, String> {
public String result = "";
#Override
protected String doInBackground(String... urls) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://bla/index.php?" + urls[0]);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
// convert response to string
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();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
}
}
And this is part of my Activity code that creates the thread class...
public class ListActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
PostRequest task = new PostRequest();
task.execute(new String[] { "action=getUsers" });
task.onPostExecute(task.result) {
}
}
public void Display(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
String value = json_data.getString("name");
TextView text = (TextView) findViewById(R.id.value);
text.setText(value);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
pass the activity reference in constructor......
as
public class PostRequest extends AsyncTask<String, Void, String> {
public String result = "";
private Activity mActivity;
public PostRequest(Activity activity){
super();
mActivity = activity;
}
......
You don't have to do a onPostExecute() as this is called after the process doInBackground has completed and then you can use the reference of the activity passed into the constructor of the AsyncTask to run any time of method on your UI.
Just remember that onPostExecute() method runs on a UI thread so here from this method you can try to modify your view if needed.
See this question...can-i-put-asynctask-in-a-separate-class-and-have-a-callback and the accepted answer. If you want a re-usable AysncTask as a stand-alone class then using a listener as a callback for all of your activities is the best way to do it.