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);
}
Related
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.
I am trying to send a HTTP Post request in Android application.
This is what should I send:
This is what should I receive:
So, to conclude, I need to get cookies from response and response code should be 302.
I have a following Android code:
private static String makePostRequest() {
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("http://g1.botva.ru/login.php");
boolean flag = httpClient.getParams().isParameterTrue(ClientPNames.HANDLE_REDIRECTS);
httpPost.addHeader("Accept", "*/*");
httpPost.addHeader("Accept-Encoding", "gzip, deflate");
//httpPost.addHeader("Content-Length", "83");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.addHeader("User-Agent", "runscope/0.1");
Header [] arr = httpPost.getAllHeaders();
String result123 = "";
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
nameValuePair.add(new BasicNameValuePair("do_cmd", "login"));
nameValuePair.add(new BasicNameValuePair("server", "1"));
nameValuePair.add(new BasicNameValuePair("email", "avmalyutin#mail.ru"));
nameValuePair.add(new BasicNameValuePair("password", "avmalyutin1234"));
nameValuePair.add(new BasicNameValuePair("remember", "1"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
String getCookie = response.getHeaders("Pragma").length + "";
result123 = response.getStatusLine().getStatusCode()+"";
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
return result123;
}
And I receive code 200. And there is only PHPSESSIONID in Cookies, but there are no other cookies.
You will need to instrument the DefaultHttpClient so that you can see the WIRE and the HEADERS.
Google log WIRE HEADERS for the client you are using. If you can not figure out the logging debug ( you may want to consider DIFF client )
Then, compare the 2 frameworks doing the post (your test harness VS android ) just narrowing the differences between what headers + POST BODY are being sent. As you get android to converge with your test harness, the android will produce the same 302 result you report getting from the test harness.
Adding function
con.setInstanceFollowRedirects(false);
resolve the problem and it stops redirecting. And also I received code 302 as desired.
Thanks everybody for help
Hi i am trying to connect to Salesforce with the Rest API and i want to retrieve sObjects..Implementing as below
void getsObjects() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://na14.salesforce.com/services/data/v24.0/sobjects");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("X-HostCommonName", "ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("X-PrettyPrint", "1"));
nameValuePairs.add(new BasicNameValuePair("Host", "ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("X-Target-URI", "https://ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePairs.add(new BasicNameValuePair("Connection", "Keep-Alive"));
nameValuePairs.add(new BasicNameValuePair("Authorization", "00D90000000qUEp!AQQAQNnuPZqEX2oqAkeQLmvq.qsBfKIMa3GCJvE7atLv2Cjy94YZn5ezRH0bosXTFthnoMNt.WpDturXB1Ijxxxxxxxxxx"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("Content-Type","application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
System.out.println("Final response"+result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
even if i am passing the the Authorization key , it is giving INVALID SESSION error
12-11 14:50:18.108: W/DefaultRequestDirector(27014): Authentication error: Unable to respond to any of these challenges: {token=WWW-Authenticate: Token}
12-11 14:50:18.498: I/System.out(27014): Final response[{"errorCode":"INVALID_SESSION_ID","message":"Session expired or invalid"}]
I am trying to connect to it from 2 days but no luck, can someone point me right direction, how to make rest calls.
The Authorization header should take the form Authorization: Bearer {sessionId} whereas you have Authorization:{sessionId}
You nameValuePairs appears to contains http headers, but you're not creating headers, you're passing them to setEntity, which sets the http body payload, not the headers.
You're creating a bunch of standard headers (like Host) which don't align with the actual url, and these aren't needed anyway.
try something like
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://na14.salesforce.com/services/data/v24.0/sobjects");
httpPost.setHeader("Authorization" , "Bearer " + sessionId)
StringEntity entity = new StringEntity("someJson", "UTF-8");
entity.setCotnentType("application/json");
httpPost.setEntity(entity)
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
System.out.println("Final response"+result);
You might also want to checkout the Force.com Android SDK which has a bunch of helpers for accessing the API.
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
I am trying to retrieve a response from my server which ultimately redirects to a URL after post data is submitted. I figured I could retrieve the url response that the server redirects with , with the code below but every time I do i get a fatal error out of memory. I was wondering what may cause this error if any one had any ideas of why I am getting this error or if this is an incorrect way? I have tested I am sending the data correctly to the server but keep getting this error. here is my code.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("token", token));
nameValuePairs.add(new BasicNameValuePair("key", "test"));
nameValuePairs.add(new BasicNameValuePair("mac", "test"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Log.d("URL", responseBody);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}