curl equivalent in Java using commons HttpClient - java

I am using Commons HttpClient to send a post request along with some string content as parameter. Following is my code:
// obtain the default httpclient
client = new DefaultHttpClient();
// obtain a http post request object
postRequest = new HttpPost(stanbolInstance);
postRequest.setHeader("Accept", "application/json");
// create an http param containing summary of article
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", content));
try {
// add the param to postRequest
postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// obtain the response
response = client.execute(postRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here, stanbolInstance is: http://dev.iks-project.eu:8081/enhancer
It does not work. Following is the exception:
Problem accessing /enhancer. Reason:
<pre> The parsed byte array MUST NOT be NULL!</pre></p><h3>Caused by:</h3><pre>java.lang.IllegalArgumentException: The parsed byte array MUST NOT be NULL!
Following is the cURL equivalent which works:
curl -X POST -H "Accept: text/turtle" -H "Content-type: text/plain" --data "The Stanbol enhancer can detect famous cities such as Paris and people such as Bob Marley." http://dev.iks-project.eu:8081/enhancer
Help!

I think you're putting the content in the wrong way.
Replace:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", content));
try {
// add the param to postRequest
postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
with
postRequest.setEntity(new StringEntity(content));

Related

How to send Header using HTTP in JAVA

I have this command.
# curl --header "Authorization: key=$api_key" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"ABC\"]}"
it is sending push notification in my device. Now I am trying java to sending it but my code is not working.
String body = "{\"registration_ids\":[\"ABC\"]}";
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
StringEntity stringentity = new StringEntity(body, "UTF-8");
httppost.addHeader("Content-Type","application/json");
httppost.addHeader("Authorization: key", "AIza*********YUI");
httppost.setEntity(stringentity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String strresponse = null;
if (entity != null) {
strresponse = EntityUtils.toString(entity);
System.out.println("strresponse = "+strresponse);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am confuse what i am missing. This doc http://developer.android.com/google/gcm/http.html#request told that i needs to send header with body.
Based on your curl example, this should be your Authorization header:
httppost.addHeader("Authorization", "key=AIza*********YUI");
This should resolve your issue. I just confirmed this header with the referenced documentation.

Android Post data with CustomHttpClient.executeHttpGet

I am calling a url by following method
try {
urlcont= URLEncoder.encode(urlcont, "utf-8");
response = CustomHttpClient.executeHttpGet("http://www.myurlhere");
} catch (Exception e) {
e.printStackTrace();
}
URL called successfully but I want to post some data (in String urlcont ) so i can get it by $_POST['urlcont'];
Thanks
try this
public void postData() {
// 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("name", "your name"));
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
}
}

Error HTTP 422 GET in Android

I'm trying to perform a GET request to the server that returns me a JSON file. But I am getting an error in the HTTP statusLine / 422. Anyone know why. Below I show how I'm doing
public void testConverteArquivoJsonEmObjetoJava() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://safe-sea-4024.ppooiheroku4554566adffasdfasdfalaqwerpcp.com/crimes/mobilelist");
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
get.getParams()
.setParameter("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJ88888a6JhMs=");
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(get);
String jsonDeResposta = EntityUtils.toString(httpResponse
.getEntity());
System.out.println();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Usually you do not specify a Content-Type header with a GET request. This header tells the server how to interpret the entity includes in the message. It is possible that the server side is expecting a JSON entity even though GET cannot include a body. Try removing the Content-Type header.
I tried the URL that you cleverly changed and got it to work fine. However, I did get a 422 when I specified a different token query parameter. Being that the status line is missing a phrase, I would assume that the Ruby application is generating it.
I managed to solve the problem. I was passing the parameter so wrong. According to this post [blog]:How to add parameters to a HTTP GET request in Android? "link". This method is used to that I kind of POST request
this method is correct
public void testConverteArquivoJsonEmObjetoJava() {
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token","0V1AYFK12SeCZHYgXbNMew==$="));
String paramString = URLEncodedUtils.format(params, "utf-8");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://safep.com/crimes/mobilelist" + "?"
+ paramString);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(get);
String jsonDeResposta = EntityUtils.toString(httpResponse
.getEntity());
System.out.println();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`

cURL using httppost in android java

I'm trying to get a cURL request work in android using the httpclient.
curl -k -X POST \
-F 'image=#00001_1.png;type=image/png' \
-F 'svgz=#00001_1.png;type=image/svg+xml' \
-F 'json={
"text" : "Hello world!",
"tid" : "0010",
"timestamp" : "1342683312",
"location" : [ 22793, -553.3344],
"facebook" :
{
"id": "4444444",
"access_token": "7FUinHfxsCTrx",
"expiration_date": "1358204400"
}
};type=application/json' \
https://example.com/api/posts
This is the code that's giving me a BAD REQUEST ERROR (400) from SERVER.
public static void example() {
HttpClient client = getNewHttpClient();
HttpPost httpost = new HttpPost("https://example.com/api/posts");
httpost.addHeader("image", "#00001_1.png; type=image/png");
httpost.addHeader("svgz", "#00001_1.png; type=image/svg+xml");
httpost.addHeader("type", "multipart/form-data");
// httpost.setHeader("Content-type", "multipart/form-data");
JSONObject data = new JSONObject();
JSONObject facebook = new JSONObject();
JSONArray location = new JSONArray();
HttpResponse response = null;
try {
data.put("text","Hello world!");
data.put("templateid","0010");
data.put("timestamp","2012-07-08 09:00:45.312195368+00:00");
location.put(37.7793);
location.put(-122.4192);
data.put("location", location);
facebook.put("id", "4444444");
facebook.put("access_token", "7FUinHfxsCTrx");
facebook.put("expiration_date", "1358204400");
data.put("facebook", facebook);
System.out.println(" ---- data ----- "+data);
StringEntity stringEntity = new StringEntity(data.toString(), "utf-8");
httpost.setEntity(stringEntity);
try {
response = client.execute(httpost);
System.out.println(" --- response --- "+response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if(entity != null) {
// A Simple Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
System.out.println(" ---- result ---- "+result);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
It works perfect from the command line, don't where I'm going wrong. Any help highly appreciated.
Also let me know if I can do it without using any library written in C (Libcurl, etc).
Thanks.
You have used stringEntity to post data. Try using UrlEncodedFormEntity to send data. Here one example how to do:
try {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("loginId", username.toString()));
nvps.add(new BasicNameValuePair("password", password.toString()));
nvps.add(new BasicNameValuePair("_eventId_submit", "Submit"));
HttpPost httppost = new HttpPost("url2");
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpParams params = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(params, 45000);
HttpConnectionParams.setSoTimeout(params, 45000);
// Perform the HTTP POST request
HttpResponse response = client.execute(httppost);
status = response.getStatusLine().toString();
if (!status.contains("OK")) {
throw new HttpException(status);
}
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
cookie = cookies.get(i);
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

postData cannot be resolved to a type

I'm new to Android programing. I'm trying to post some data to a server using post. I googled it up and came up with this:
public void postData() {
// 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
}
}
My problem is I'm getting errors on the first line of this code:
postData cannot be resolved to a type
syntax error on token "{", delete this token
syntax error on token "void", # expected
I'm using Eclipse and I used Shift+Ctrl+o to get all the imports.
You problem (based on the information you've given so far) is that you're declaring the function postData outside of a class.
Functions in Java need to be declared in a class. Either, you've accidently close off the previous class by having one too many } (in which case you should have an error at the extra }), or you haven't declared a class.
The class could look something like this:
public class MyPoster {
public void postData() {
// 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
}
}
}

Categories

Resources