HTTP Post not working in my mobile - android

I am sending phone contacts as a json array to php server. It is sent successfully from HTC mobile. But not working in Samsung galaxy. Any idea?? Here is my code which works fine in HTC device.
public void postData(String id) {
String URL = "http://www.aheadsupapp.com/app/functions/save_phone_friends.php";
JSONArray Jarray = new JSONArray();
Jarray = fetchContacts();
ArrayList<NameValuePair> nVP = new ArrayList<NameValuePair>(2);
nVP.add(new BasicNameValuePair("uid", id ));
nVP.add(new BasicNameValuePair("json", Jarray.toString()));
Log.d("Response","Entered Post");
try{
HttpPost post = new HttpPost(URL);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000); //Timeout Limit
post.setEntity(new UrlEncodedFormEntity(nVP, "utf-8"));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String phpResponse = client.execute(post, responseHandler);
Log.d("Response", "PHP Response: " + phpResponse);
}
catch(Exception e){
e.printStackTrace();
Log.d("Response", "Catch: " + e.getMessage());
}
}

I am sure it depends on the Android version. Remember that you should not perform any interent activity in the main thread.You should use AsyncTask or Hanlders.
In older versions of Android it was allowed to run internet consuming threads in the main one , but since 4.0 it was denied.

Related

Cant authenticate my ACS token

Ive been trying to send messages to a azure service bus queue from android for a while and i just cant get it to work. This is the code i use for getting the ACS SWT:
private void getTokenFromACS() throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://servicebusnamespace-sb.accesscontrol.windows.net/WRAPv0.9/");
List<NameValuePair> parameters = new ArrayList<NameValuePair>(3);
parameters.add(new BasicNameValuePair("wrap_name", "name"));
parameters.add(new BasicNameValuePair("wrap_password", "password associated with the name"));
parameters.add(new BasicNameValuePair("wrap_scope", "Realm url"));
httppost.setEntity(new UrlEncodedFormEntity(parameters));
BasicHttpResponse httpResponse = null;
httpResponse = (BasicHttpResponse)httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String[] tokenVariables = URLDecoder.decode(reader.readLine()).split("&wrap_access_token_expires_in=");
authorizationToken = tokenVariables[0];
}
This works fine, i get a string that has the wrap_access_token, issuer, audience, expiresOn and HMACSHA256.
What i try to do after that is to send a message with this token like this:
HttpClient requestClient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://servicebusnamespace.servicebus.windows.net/queuename/messages");
post.addHeader("Authorization", "WRAP access_token=\""+authorizationToken+"\"");
Item item = new Item();
Date date = new Date();
item.setDate(date);
item.setId(1);
item.setRoadName("roadname");
item.setSpeed(60.0);
item.setLat(12.12);
item.setLng(12.12);
String json = new GsonBuilder().create().toJson(item, Item.class);
post.setEntity(new ByteArrayEntity(json.getBytes("UTF8")));
HttpResponse httpResponse = requestClient.execute(post);
This always result in my Token not being authenticated, i get the error message saying my token doesnt containt a signature or that it doesnt have the audience set. What could be wrong?
Note that this is on android =)
Thanks in advance!
Seems like you are missing some code. Your authorizationToken is currently something like this: "wrap_access_token=net.windows.servicebus.action%3dLis..."
The only thing you want is the part after the equal-sign.
I think this will do:
String[] tokenVariables = URLDecoder.decode(reader.readLine()).split("&wrap_access_token_expires_in=")[0].split("=");
authorizationToken = tokenVariables[1];

Receiving Data on the servlet From Android?

I am trying to send data to from my android app to the servlet using POST method but servlet don't show any kind of the activity just null has shown in the output. Although I am receiving response from servlet on the android app using GET method.
We try to print action on logcat. It shows that data has been sent but show null on browser.
I am also receiving exception "Invalid use of single client connection manager:Connection still allocated"
Android Code:-
String url = "http://10.0.2.2:8084/AndroidApp/AndroidServlet";
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost httpPost = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Name", name));
nameValuePairs.add(new BasicNameValuePair("Father", father));
nameValuePairs.add(new BasicNameValuePair("Gender", gender));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
String response = httpClient.execute(httpPost, res);
}
Servlet Code:-
public class AndroidServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
String Name=request.getParameter("Name");
String Father=request.getParameter("Father");
String Gender=request.getParameter("Gender");
try (PrintWriter out = response.getWriter()) {
out.println("Hello Android !!!!");
out.println( Name + " " + Father + " " + Gender + " ");
}
}
Output on Browser:-
Hello Android !!!!
null null null
It's difficult to debug net apps without external tools and of course it will be difficult to find bug in your code without compiling it.
For debugging such apps I use Android Emulator + WireShark to look at the body of HTTP request. Hope it'll help.
Edited:
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
String strResponseSaveGoal =
httpclient.execute(httppost, responseHandler);
Log.d("sendCancelOrderRequest", strResponseSaveGoal);
}catch ( ConnectTimeoutException conEx )
{
handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
}
catch (ClientProtocolException ex) {
Log.d("sendCancelOrderRequest","");
handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
}catch (IOException ex) {
Log.d("sendCancelOrderRequest","");
handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
}

Create this string exactly in Android

I want to build 2 same products for Android and iOs.
The iOs already works, but the android doesnt, that's because of the format of the string.
in iOs this is:
NSString*jsonString = [[NSString alloc] initWithFormat:#"{\"id\":\"%#\",\"longitude\":\"%#\",\"latitude\":\"%#\",\"timestamp\":\"%#\"}", _phonenumber, longitude , latitude, stringFromDate];
And i dont know how to do this exactely like this in android. The format here is different.
What i have now is:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("id", num));
nameValuePairs.add(new BasicNameValuePair("longitude", longi));
nameValuePairs.add(new BasicNameValuePair("latitude", lat));
nameValuePairs.add(new BasicNameValuePair("timestamp", time));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Thanks in advance, i need this by the end of the week so if you could help me, that would be greatly appreciated
i get this as an result from the iOs string:
{
"id":"0612833398",
"longitude":"-143.406417",
"latitude":"32.785834",
"timestamp":"10-10 07:56"
}
Okay, this is what my problem is.
Yes i need to send this exact string to an asp.net file on a server. But i need to know how to combine this with this: with the http post to
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
before i combined this with the nameValuePPairs like this
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Create same string as you are getting in IOS by create an JosnObject as:
JSONObject json = new JSONObject();
json.put("id", "0612833398");
json.put("longitude", "-143.406417");
json.put("latitude", "32.785834");
json.put("timestamp", "10-10 07:56");
now if you make a print for json object you will get this string :
{"id":"0612833398","longitude":"-143.406417","latitude":"32.785834",
"timestamp":"10-10 07:56"}
and Post JSONObject as to server :
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
httppost.setHeader("Content-type", "application/json");
// Create json object here...
JSONObject json = new JSONObject();
json.put("id", "0612833398");
json.put("longitude", "-143.406417");
json.put("latitude", "32.785834");
json.put("timestamp", "10-10 07:56");
/// create StringEntity with current json obejct
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
}
To create a String you can use String.format(). In this case the syntax is very similar to Objective-C:
String s = String.format("{\"id\":\"%s\",\"longitude\":\"%s\",\"latitude\":\"%s\",\"timestamp\":\"%s\"}", num, long, lat, time);
HTTP Post goes like this:
HttpPost postMethod = new HttpPost(url);
try {
HttpParams params = new BasicHttpParams();
params.setParameter(name, value);
postMethod.setParams(params);
httpClient.execute(postMethod);
} catch (Exception e) {
} finally {
postMethod.abort();
}

Android Getting JSON return error from POST Http execution

I'm currently trying to send data via POST to a server, and the server is handling the data and appends it to a JSON file. I'm currently getting a 422 error and I've been receiving it for a while now. My question is: How do I receive that JSON error itself in Java so that I can see what the error is. All I'm seeing is a HttpResponseException and it doesn't give me anything else. Thanks for the time and help in advance.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mPath);
// Add your data
try
{
List nameValuePairs = new ArrayList(4);
httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(bundleId).append(":").append(apiKey).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP));
nameValuePairs.add(new BasicNameValuePair("state", "CA"));
nameValuePairs.add(new BasicNameValuePair("city", "AndDev is Cool!"));
nameValuePairs.add(new BasicNameValuePair("body", "dsads is assrawstjljalsdfljasldflkasjdfjasldjflasjdflkjaslfggddsfgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfddjflaskjdfkasjdlfkjasldfkjalskdjfajasldfkasdlfjasljdflajsdfjasdjflaskjdflaksjdfljasldfkjasljdflajsasdlfkjasldfkjlas!"));
nameValuePairs.add(new BasicNameValuePair("title", "dsaghhhe fd!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost);
//int status = response.getStatusLine().getStatusCode();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Log.v(TAG, "response: " + responseBody);
//JSONObject response = new JSONObject(responseBody);
int f = 0;
}
catch(HttpResponseException e)
{
Log.e(TAG, e.getLocalizedMessage());
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
you may send your parameters more conveniently by using predefined Json class as below:
String jsonParam = null;
try{
JSONObject param = new JSONObject();
param.put("state", "CA");
param.put("city", "AndDev is Cool!");
//and so on with other parameters
jsonParam = param.toString();
}
catch (Exception e) {
// TODO: handle exception
}
and set the post entity as:
if(jsonParam != null)
httppost.setEntity(new StringEntity(jsonParam, HTTP.UTF_8));
422 error says: Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors
You got a problem with UrlEncodedFormEntity

How to set header using http post method

i am currently working on one application..
in that application i have to use get and post both methods..
get method works properly but in post method suddenly i get the response like
"invalid method.post required"..
my code for that is:
String list_url = "************************";
try {
String appand = TimeStampForAuth.TimeStameMethod(main.this);
String auth = android.util.Base64.encodeToString(("iphone" + ":" +
"2a5a262d5a")
.getBytes("UTF-8"), android.util.Base64.NO_WRAP);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(list_url+appand);
Log.d("URL_LIST", list_url+appand);
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("login",Login));
nvps.add(new BasicNameValuePair("password",password));
nvps.add(new BasicNameValuePair("title",title));
nvps.add(new BasicNameValuePair("category_id",cat_id));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
post.addHeader("Authorization", "Basic " + auth);
post.setEntity(p_entity);
HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
String s = EntityUtils.toString(responseEntity);
Log.d("List response", s);
}
catch(Exception e){
System.out.println(e.toString());
}
in that i am missing somethinf or what that i dont know..is all that thing is valid for post method....
please help me as early as possible...
thanking you.........
Try using setHeader() instead of addHeader()
You could try HttpClient 4.1 for Android: http://code.google.com/p/httpclientandroidlib/
(There are bugs in the HttpClient version 4.0 which Android uses.)
You can also debug with it a little more with httpClient.log.enableDebug(true);
If you don't want to use an external library, I'd start debugging the network traffic.
With a software called Wireshark you can see and inspect all Http Requests/Responses very
easily.
For authorization I personally would use:
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(hostname, port),
new UsernamePasswordCredentials(user, pass));
use this instead:
HttpURLConnection connection = (HttpsURLConnection) serviceURL.openConnection();
connection.setRequestMethod("POST");

Categories

Resources