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.
Related
I'm trying to access one of IBM Watson RESTful interfaces (speech to text) from a Java client using Apache HttpPost, but failing to upload a binary .wav input file properly.
The following 'curl' command works just fine, producing correct results:
curl -u "user:password" -H "content-type: audio/wav" --data-binary #"newfile.wav" "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" -X POST
The Java client below intends to replicate above curl functionality:
public void speech2text(String user, String password, String file_name) {
try {
String ulr_string = "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ulr_string);
httpPost.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials(user, password), "UTF-8", false));
httpPost.addHeader("content-type", "audio/wav");
httpPost.addHeader("content-type", "multipart/form-data");
// httpPost.addHeader("transfer-encoding", "chunked");
File input_file = new File(file_name);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", input_file, ContentType.DEFAULT_BINARY, "c:\\Temp\\newfile.wav");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
System.out.println("executing request " + httpPost.getRequestLine());
Header headers[] = httpPost.getAllHeaders();
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) {
EntityUtils.consume(resEntity);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But the request fails, returning:
HTTP/1.1 400 Bad Request
{
"code_description": "Bad Request",
"code": 400,
"error": "unable to transcode data stream audio/wav -> audio/x-float-array "
}
Watson's API requires chunked transfer encoding for large files, but the sample I'm working with is pretty small.
I've never really used http requests in Java, I'm trying to make a request that would basically recreate this http://supersecretserver.net:8080/http://whateverwebsite.com
This server takes whatever website and returns only the text of the page in the body of the response.
The code is as follows:
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://supersecretserver.net:8080/" + "http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
It seems to get stuck on
response = client.execute(request);
I'm not sure what the problems is, any insight would be helpful.
Seems likely that your HttpClient is not timing out, you can set a timeout value by following this example (from http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/)
You just to have to consider a timeout value that makes sense for you.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMillis);
Also as your HttpClient is not connecting (since it's getting stuck) you should also take into consideration why is that happening (maybe you need to configure a proxy?)
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));
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();
}
}`
I am trying to post xml on android. Same xml and server works on iphone perfectly, but on android i am getting invalid xml error message.
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://stage.isadiasjd.com.tr/asdasdad-web/getProductDeviceService.do");
try {
StringEntity se = new StringEntity("<customer><districtId>2541</districtId><barcode>45464654654917</barcode><udid>dade51ce2c127310d1df5ee25e876e46feae470b</udid><email>Xzcxzcxzczxc#zxczxcxczxc.com</email><hashCode>2500a7005c01903093fa268984zczczczaeawdwa2w1d3w6dec9b61afbe28f37baad819ba3e0d</hashCode></customer>", "UTF-8");
// se.setContentType("text/xml");
se.setContentType("application/atom+xml");
httppost.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
String ss = EntityUtils.toString(resEntity);
Log.v("http req", ss);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.v("ex","1");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v("ex","2");
e.printStackTrace();
}
}
Try application/json. On Android 2 something wrong with xml responses on some models