I tried to request the URI bellow and parse it response a lot of ways. But I don't know what is the problem with my code below.
String url = "http://10.0.2.2/ipf/conx.php";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
Log.v("Log1", "msg1");
HttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
Log.v("Log1", "msg2");
HttpResponse response = httpclient.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
Log.v("Log2", "msg1");
} else {
Log.v("log2", "msg2");
}
When I follow my logcat print, I can see only:
log1( msg1 and 2 )
Please take some help
thanks
It takes sometime(depends upon your internet speed) to get the response from the server....!
Or you can use below class to check when the response come,
private class xyz extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog ;
private Activity mActivity;
public xyz(Activity activity)
{
this.mActivity = activity;
}
protected void onPreExecute() {
this.dialog = new ProgressDialog(mActivity);
this.dialog.setMessage("Please Wait...");
this.dialog.show();
//code which load at prefix time
}
#Override
protected Void doInBackground(Void... arg0) {
// make code which you want in background
String url = "http://10.0.2.2/ipf/conx.php";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
Log.v("Log1", "msg1");
HttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
Log.v("Log1", "msg2");
HttpResponse response = httpclient.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
Log.v("Log2", "msg1");
} else {
Log.v("log2", "msg2");
}
return null;
}
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
Use this this in your activity class like this,
new xyz(ActivityClassName.this).execute();
There is a possibility of 2 issues here.
1- check if you have added proper network permissions to your AndroidManifest.xml file.
2- your code is executing a network request directly on main thread which Android does not allow. You have to execute this in worker thread e.g. use AsyncTask
It will be much better if you also put the log in your question.
Related
the following code is for make and httpost request to a server always response 404
but if i make the same request on postman works fine i send only one parameter on post an base 64 image string
private class SendData extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... strings) {
// Create a new HttpClient and Post Header
try{
MobileUtil.HTTP_PARAMS = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(MobileUtil.HTTP_PARAMS, MobileUtil.HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(MobileUtil.HTTP_PARAMS, MobileUtil.HTTP_TIMEOUT);
MobileUtil.HTTP_CLIENT = new DefaultHttpClient(MobileUtil.HTTP_PARAMS);
MobileUtil.HTTP_CLIENT = sslClient(MobileUtil.HTTP_CLIENT);
HttpPost post = new HttpPost("http://aplicacion.fractal.com.pe:9090/fractalMobile/mobile/guardarFotoTest");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("foto",encodedImage));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse resp = MobileUtil.HTTP_CLIENT.execute(post);
Log.d("Info",resp.getStatusLine().getReasonPhrase());
Log.d("Info",resp.getStatusLine().toString());
String respStr = EntityUtils.toString(resp.getEntity());
Log.d("Info",respStr);
if(respStr.equals("1"))
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,"Se Realizo la Operacion con Exito",Toast.LENGTH_LONG).show();
}
});
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
and i try to debug but don't know what is wrong on postman the request response with 1 if ok and 0 if go wrong
any idea how to make the request
I have an app that should send a the phone number and retrieve a value from the database, now I change the query and my code should retrieve values of multiple columns, So where changes should be in my code.
public class JSONTransmitter extends AsyncTask<JSONObject, Void, String>
{
HttpResponse response;
String url = "http://192.168.1.97:89/Derdeery/bankOsman.php";
private AsyncCallback asyncCallback;
public JSONTransmitter(Context context) {
// attach the callback to any context
asyncCallback = (AsyncCallback) context;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
asyncCallback.onResponse(result);
}
protected String doInBackground(JSONObject... data)
{
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
String resFromServer = "";
try {
StringEntity se = new StringEntity("json=" + json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
Log.i("Response from server", resFromServer);
} catch (Exception e) {
e.printStackTrace();
}
return resFromServer;
}
public static interface AsyncCallback {
void onResponse(String res);
}
}
Here is something to consider:
First, in your php code (server-side), query your data perhaps separately. So for instance, you can get those that match column A and then query for those that match column B.
Generate Json for each (A and B accordingly)
Then create a single JSON object that contains the two sets of data like this:
{
"DataFromColumnA" : {},
"DataFromColumnB" : {}
}
Once you have made your HTTP request in your android code, you can get the specific data by getting "DataFromColumnA" json Object and B respectively.
I hope this helps you get your problem solved!
Im trying to send an image to a REST service using Sending images using Http Post. The post is quit informative but i get a compiling error at FileBody bin1 = new FileBody(file);.
Error: The constructor FileBody(File[]) is undefined
Which is weird because i define it, why is this happenig and whats the solution to fixing it?
Any help is greatly appreciated.
Code Source:
private class ImageUpload extends AsyncTask<File, Void, String> {
#Override
protected void onPreExecute() {
if (checkNullState() == false) {
showMyDialog();
}
}
protected String doInBackground(File... file) {
String imageDescriptionTemp = "Photo Temp Description.";
String PostRequestUri = "https://demo.relocationmw.com/ws_docmgmt/Service1.svc";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(PostRequestUri);
FileBody bin1 = new FileBody(file);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("Image", bin1);
post.setEntity(entity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_string = EntityUtils.toString(resEntity);
if(resEntity != null){
Log.i("RESPONSE", response_string);
}else{
return null;}
}
#Override
protected void onPostExecute(String result) {
if (checkNullState() == true) {
dismissMyDialog();
}
// add location once we have that figured out.
Toast.makeText(HomeActivity.this, "Image can be viewed {Location}",
Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Map... values) {
}
I think that what you want is
FileBody bin1 = new FileBody(file[0]);
beacuse doInBackground uses varargs. So the following line of code:
doInBackground(Params... params)
is equivalent to
doInBackground(Params[] params)
and when you do
FileBody bin1 = new FileBody(file)
file is an array (And I suppose that you have defined the constructor like this FileBody(File file))
I am not reaching an onPostExecute in an AsyncTask Class.
I call the task this way, inside an onClick in a dialog box:
new HelpfulTask().execute(passing);
Note: When I hover over the above code, I get a warning:
A generic Array of ArrayList is created for a varargs
parameter.
I am not sure what that means and if that is preventing my Task from even running?
Here is the Task Code:
protected class UnHelpfulTask extends
AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ArrayList<String> passed;
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
passed = passing[0];
String url_select = "http://www.---.com/---/bad.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", passed.get(0)));
param.add(new BasicNameValuePair("text", passed.get(1)));
param.add(new BasicNameValuePair("category", passed.get(2)));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
return null;
}
InputStream is = null;
String result = "";
protected void onPostExecute(Void v) {
Toast.makeText(getContext(), "You have voted this down!",
Toast.LENGTH_SHORT).show();
}
}
I get no errors on run and in the onPostExecute, the Toast never shows. (Note: This is an inner class inside of an ArrayAdapter.) I also added a toast to see if my ArrayList was unwrapping properly and put that in the onPostExecute but it never showed either.
How can I test to see if this Task is even running?
Change
protected void onPostExecute(Void v) {
so it is
protected void onPostExecute(ArrayList<String> arr)
Or change your AsyncTask declaration so it
extends AsyncTask<ArrayList<String>, Void, Void>
Which is the better idea since you return null in doInBackground(). The reason why you weren't getting the toast is because you were making a different method than what your AsyncTask specifies. This is why we ususally use the #Override annotation - it forces a check for actual overrides, which you need to do in classes like AsyncTasks.
I have an activity that create a new instance of connection. like this:
public class myActivity extends Activity {
TextView tv;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_news);
gestureDetector = new GestureDetector(new SwipeGestureDetector());
tv = (TextView) findViewById(R.id.tx);
dialog = ProgressDialog.show(myActivity.this, "","Validating user...", true);
connection con = new connection(dialog);
final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
dialog.dismiss();
}
});
}
}
in connection class i have an HttpResponse that returns null. like this:
public class connection {
private HttpPost httppost;
private HttpClient httpclient;
private HttpResponse response;
private ProgressDialog dialog = null;
private String result;
public connection(ProgressDialog di){
dialog = di;
}
public String connect_to_db(String url){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost(url);
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpclient.execute(httppost, responseHandler);
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
return result;
}
}
why the value of "result" in connection class is null?
This line:
final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");
Should not be written in the onCreate, but rather in a separate thread => NetworkOnMainThreadException
For your NullPointer, please tell us if you have the Internet permission in Manifest and if response is null or not.
May be because you are doing network operation in onCreate Method. It will not create any problem if you are using android2.2, but if it is HoneyComb then chances are that it is causing some exception and finally you are getting null value. Move the code to onResume() method.
For Simplicity use
HttpResponse response = httpclient.execute(httppost);
and
String valueString = EntityUtils.toString(response.getEntity());
int statusCode = response.getStatusLine().getStatusCode();
print these values and see the out put.