Sending HttpPost to Server; No Response needed - java

I want to do an HttpPost on Android to update a single row in a database. I do not need any response, verification, etc. So I am trying to simplify my code because I think what I have may be redundant.
This is what I have:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
Do I need all of this? It seems I can just have
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
Is this correct?

I won't eat when I'm not hungry :)
Yes. The second part is good enough. No need to get the response object there if you don't really need it. That is fine.

You may also want to check AQuery library which simplifies Http connections:
https://code.google.com/p/android-query/

Related

Is my HTTPClient connection leaking sockets?

I have an app deployed on google app engine that uses the Apache HTTPClient. Recently as the app is getting more traffic, I have started running into exceptions where the sockets quota has been exceeded. The exception is
com.google.apphosting.api.ApiProxy$OverQuotaException: The API call remote_socket.SetSocketOptions() required more quota than is available.
I reached out to the App Engine team and they wanted me to check if my app was leaking sockets.
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.spark.com");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("param1", "val1"));
nvps.add(new BasicNameValuePair("param2", "val2"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpclient.execute(httpPost);
Document doc = null;
try {
HttpEntity entity = response.getEntity();
doc = Jsoup.parse(entity.getContent(), "UTF-8", "");
EntityUtils.consume(entity);
} finally {
response.close();
httpclient.close();
}
This is what my http connection code looks like. Am I doing something wrong which may be causing the sockets to leak? Can I do something better?
this work for me :
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
// HttpPost httppost = new HttpPost("http://rafsanjan.uni-azad.my.com/json/darkhasr.php?shdaneshjo="+value_id+"&moavenat="+value_seaction+"&darkhast="+zir_item+"&startdate=test&tozih="+ value_descration); //???
try {
URIBuilder builder = new URIBuilder();
builder.setScheme("http")
.setHost("app.my.ac.com")
.setPort(1180)
.setPath("/json2/darkhasr.php")
.addParameter("shdaneshjo", value_id)
.addParameter("moavenat", value_seaction)
.addParameter("darkhast", value_item)
.addParameter("startdatet", "0")
.addParameter("tozih", value_descration)
.build();
// .fragment("section-name");
String myUrl = builder.toString();
Log.d("url=>",myUrl);
HttpPost httppost = new HttpPost(myUrl);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(8);
//nameValuePairs.add(new BasicNameValuePair("name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Log.d("RESPONSE",EntityUtils.toString(resEntity));
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}

HTTP get and post in android

in my program I have http get which gets data from PHP script. This code is present in async task. This works fine.
But now I want to do HTTP post, where I, the android client, post data to the PHP script, it quires the DB and returns the result of that.
But this is what is confusing me.
Can I get a response from a HTTP post? Or do i need a combination of post and get?
This question I don't expect an answer but if anyone can advise on this would be great. I have one async task which does the HTTP get. Now i want to use the same async to do either HTTP get or post but not both. Is this possible?
Thank you
Here John. A small snippet. My problem is the HTTP StatusLine httpStatus and http entity it does not recognise any of the responses because they are in if statements so the compiler thinks they will not be defined.
if(params[1] == "GETRESULT")
{
HttpGet get = new HttpGet(params[0]);
HttpResponse r = client.execute(get);
}
else //we are posting
{
HttpPost post = new HttpPost(params[0]);
HttpResponse r = client.execute(post);
}
StatusLine httpStatus = r.getStatusLine();
HttpEntity e = r.getEntity();
You can get a response with post
You can use the same async method as long as you have some logic that changes the request type to POST or GET depending on what you want to do.
some info on HttpPost
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
For your code to work you need to declare the Response outside of your if/blocks:
HttpResponse r = null;
if(params[1] == "GETRESULT")
{
HttpGet get = new HttpGet(params[0]);
r = client.execute(get);
}
else //we are posting
{
HttpPost post = new HttpPost(params[0]);
r = client.execute(post);
}
StatusLine httpStatus = r.getStatusLine();
HttpEntity e = r.getEntity();
Move your HttpResponse r above the if/else statement as HttpResponse someVariable; then you can access it inside your else, and read the result afterwards. You also have to check for NullPointerException, with a try / catch block.
For example like this :
HttpResponse r;
if(params[1] == "GETRESULT")
{
HttpGet get = new HttpGet(params[0]);
r = client.execute(get);
}
else //we are posting
{
HttpPost post = new HttpPost(params[0]);
r = client.execute(post);
}
StatusLine httpStatus = r.getStatusLine();
try {
HttpEntity e = r.getEntity();
} catch (NullPointerException e) {
//Error handling
}

Android HttpClient: How much data is transferred?

I'm using a PHP script to access data in my database.
However, data transfer might be expensive if your plan doesn't cover 3G access. So if there's no Wifi around, it would be good to know, how much my application is actually downloading/uploading/using.
Is there a way I can determine how much Bytes I'm uploading (post arguments) and then downloading (string output/response of the php script)?
Code in use:
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(arguments));
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity entity = httpresponse.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
Use getEntity().getContentLength() to get the HTTP message size, in HTTP request and response. And save the consumed property in SharedPreferences to recover it in another session.
The code will look like:
static long consumed = 0;
//http post
long consumedNow = 0;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(arguments));
consumedNow += httppost.getEntity().getContentLength();
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity entity = httpresponse.getEntity();
is = entity.getContent();
consumedNow += httpresponse.getEntity().getContentLength();
Log.e("log_tag", "connection success ");
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
} finally {
consumed += consumedNow;
SharedPreferences sp = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("consumed", value);
editor.commit();
}

httpclient.execute works but overloaded function throws exception

I'm writing an Android application. It sends a HTTPPost to a server and receives the answer, when I use :
public final HttpResponse execute (HttpUriRequest request)
it's ok,
but when I try to use:
public T execute (HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
it throws ClientProtocolException
because of some reasons I wanna use the second function, what should I do? What is the exception for ?
here is the code that uses the first function :
HttpPost httppost = new HttpPost("http://foo.Com/GeneralControls/Service.asmx/Login");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost) ;
and here is the code that uses the second function:
HttpPost httppost = new HttpPost("http://foo.Com/GeneralControls/Service.asmx/Login");
DefaultHttpClient httpclient = new DefaultHttpClient();
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String response = httpclient.execute(httppost , responseHandler) ;
throws ClientProtocolException.
See the below code is working fine for me
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,
Util.cookieStore);
try {
HttpResponse response = httpclient.execute(httppost,
localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But you are trying to pass ResponseHandler and it accepts httpContext
The problem was a protocol problem, the webservice was changing the Destination URL and it produced an Exception

Android post request

I have javascript code that i am trying to mimic in an android application:
Here is the javascript code:
text = '{"username":"Hello","password":"World"}';
x.open("POST", url);
x.setRequestHeader("Content-type", "application/json");
x.setRequestHeader("Content-length", text.length);
x.send(text);
and here is what i have so far for the android application(doesnt work):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
String text = "\"{\"username\":\"Hello\",\"password\":\"World\"}\"";
httppost.setHeader("Content-length",Integer.toString(text.length()));
httppost.setEntity(new StringEntity(text));
HttpResponse response = httpclient.execute(httppost);
when i try to debug this code on eclipse the emulater keeps running while the debugger hangs. Thanks!
Note: its hanging on httpclient.execute(httppost)
Here is the code I use for Android post requests:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("fullurl");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("parameter", "variable");
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
...and so on.
Try it out:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
JSONObject json = new JSONObject();
try{
json.put("username", "Hello");
json.put("password", "World");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
}
Did you mean to set your HttpPost path to just path. I think your hanging because you haven't given the HttpPost a valid URL. You'll need to modify this line:
HttpPost httppost = new HttpPost("path");
to something like
HttpPost httppost = new HttpPost("actual/url/path");
You have extra speech marks within the start and end of your text string compared to the JS version?
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(StringUrl);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println("rep => " + response);
} catch (IOException e) {
System.out.println(e);
}
}

Categories

Resources