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);
}
}
Related
I was wondering, using HttpClient and HttpPOST is there a way to post a complex JSON object as the body of the request? I did see an example of posting a simple key/value pair in the body (as shown below from this link: Http Post With Body):
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));
request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);
However, I would need to post something like the following:
{
"value":
{
"id": "12345",
"type": "weird",
}
}
Is there a way for me to accomplish this?
ADDITIONAL INFORMATION
Doing the following:
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
results in an empty body on the server... hence i get a 400.
Thanks in advance!
HttpPost.setEntity() accepts StringEntity which extends AbstractHttpEntity. you can set it with any valid String of your choice:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
This worked for me!
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
I want to make a post from my android application and insert into my database. My first approach was to send a post from my application and just show the value but it did not work.
My code from the application is
public void postData() {
HttpClient Client = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("regid", "sID"));
nameValuePairs.add(new BasicNameValuePair("etc", "sETC"));
try {
String SetServerString = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://your-url.com/script.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = httpclient.execute(httppost, responseHandler);
} catch(Exception ex) {
// failed
}
}
The php code is
<?php
include 'db.inc.php';
$device_token = urldecode($_POST['regid']);
echo $device_token;
?>
Replace your lines
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = httpclient.execute(httppost, responseHandler);
By
HttpResponse response = httpclient.execute(httppost);
You can check response in android side using
String responseStr = EntityUtils.toString(response.getEntity());
System.out.println(responseStr);
Use following PHP code to get values.
<?php
$value1 = $_POST["regid"];
$value2 = $_POST["etc"];
echo $value1;
?>
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());
}
I want to send a http request to a url with Android.
I am an iOS developer and now trying to learn Android.
I used to send the JSON string in iOS like below
{"function":"login", "parameters": {"username": "nithin""password": "123456"}}
How can I send this in Android?
I tried List<NameValuePair> but can't find the proper solution.
Full code of what I tried -
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("function", "login"));
nameValuePairs.add(new BasicNameValuePair("username", "nithin"));
nameValuePairs.add(new BasicNameValuePair("password", "123456"));
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
}
I think JsonStringer is easy and useful for you here..
Try this:
HttpPost request = new HttpPost(URL);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
vm = new JSONStringer().object().key("function")
.value(login).key("parameters").object()
.key("username")
.value(nithin).key("password").value("123456")
.endObject().endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
So I want to use the TestFairy API (url: https://app.testfairy.com/api/upload). This API call expects 3 post paramters:
api_key (string)
apk_file (.apk file)
testers_groups (string)
So far I came up with this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List <NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("testers_groups", testers));
params.add(new BasicNameValuePair("api_key", key));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("apk_file", new FileBody(file));
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
But it does not work.
Can anybody point me in the right direction?
Try something like this:
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("api_key", new StringBody(key));
entity.addPart("apk_file", new FileBody(file));
entity.addPart("testers_groups", new StringBody(testers));
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
Optionally add mime-types in the StringBody and FileBody constructors (but probably not necessary).