Anyone ever called the setlist.fm API from Android? I'm trying to execute the following code:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest;
try
{
getRequest = new HttpGet(url);
HttpResponse getResponse = client.execute(getRequest);
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (Exception e)
{
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
But I run into 2 issues it seems. The execute always seems to return correctly with a statusline of 200, but when I try to get the entity the length is -1 even though the response object shows a basichttpentity object was returned. Also, when I try to call getContent it blows up for some reason with a generic exception. A sample API call that I'm trying to use is http://api.setlist.fm/rest/0.1/search/setlists.json?artistName=Prince.
Any suggestions would be gladly welcomed.
Thanks!
I figured out the issue. It seems that the response coming back from the API is streamed and comes in chunks and I was attempting to grab the entity before it was finished. I removed this code:
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
And replaced it with:
return EntityUtils.toString(getResponse.getEntity());
Related
I want to fire a blocking call to my php file which queries my db. I want it to be blocking and not async as i don't want the user shown anything until this call is successful or not.
I run the below code, it stops at response = httpclient.execute(httpget); for a minute or two before going into catch for error. I cant see an error in the e item.
Anybody know whats going on here - my php file works with async task.
public static String blockingHttpCallToUrl(String url)
{
String result="nothingReturned";
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda", response.getStatusLine().toString());
// Get hold of the response entity
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 JSON Response Read
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
return result;
}
I am trying to post two json encoded values to my webservice using the below code. but i am not getting any response (Just Blank Output and No errors on LogCat). However, I have tried posting the same parameters from PHP to my webservice using cURL which works great.
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
try {
json.put("name","email");
json.put("email", "email");
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept-Encoding", "application/json");
post.setHeader("Accept-Language", "en-US");
List<NameValuePair> ad = new ArrayList<NameValuePair>(2);
ad.add(new BasicNameValuePair("json", json.toString()));
post.setEntity(new UrlEncodedFormEntity(ad));
Log.i("main", "TestPOST - nVP = "+ad.toString());
response = client.execute(post);
if(response!=null) {
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity,HTTP.UTF_8); //Get the data in the entity
}
} catch(Exception e) {
}
Try Getting your response by this
if (response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
}
You're catching Exception (the super class) without logging. If an exception of any kind occurs in your try block the code will jump to the catch without any log.
Change this:
catch(Exception e){
}
with
catch (Exception e)
Log.e("myappname", "exception", e);
}
If there is no response, you should definitely check your catch exception e, since you didn't write anything in the clause, there might be something happening but you didn't notice.
I have a method to connect to send post data to a webservice and get the response back as follow:
public HttpResponse sendXMLToURL(String url, String xml, String httpClientInstanceName) throws IOException {
HttpResponse response = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance(httpClientInstanceName);
HttpPost post = new HttpPost(url);
StringEntity str = new StringEntity(xml);
str.setContentType("text/xml");
post.setEntity(str);
response = httpClient.execute(post);
if (post != null){
post.abort();
}
if (httpClient !=null){
httpClient.close();
}
return response;
}
Then, in my AsyncTask of my fragment, I try to read the response using getEntity():
HttpResponse response = xmlUtil.sendXMLToURL("url", dataXML, "getList");
//Check if the request was sent successfully
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// Parse result to check success
responseText = EntityUtils.toString(response.getEntity());
if (!xmlParser.checkForSuccess(responseText, getActivity())){
//If webservice response is error
///TODO: Error management
return false;
}
}
And when I reach that line:
responseText = EntityUtils.toString(response.getEntity());
I get an exception: java.net.SocketException: Socket closed.
This behavior doesn't happen all the time, maybe every other time.
Just write
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
it should work.No need to write codes which makes confusion.
I also experienced the 'socket closed' exception when using a client instance built using HttpClientBuilder. In my case, I was calling HttpRequestBase.releaseConnection() on my request object within a finally block before processing the response object (in a parent method). Flipping things around solved the issue... (working code below)
try {
HttpResponse response = httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
// Do something interesting with responseBody
} catch (IOException e) {
// Ah nuts...
} finally {
// release any connection resources used by the method
request.releaseConnection();
}
I am using http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java for Android.
I set the response using the following code:
HttpResponse getResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
getResponse.setEntity(new StringEntity(new String("The requested resource " + target + " could not be found due to mismatch!!")));
conn.sendResponseHeader(getResponse);
conn.sendResponseEntity(getResponse);
My response in Mozilla Poster or browser has the header 404 and the response body as:
The requested resource could not be found due to mismatch!!HTTP/1.1 200 OK
How can I get only the HTTP body String? Why am I getting HTTP/1.1 200 OK in response. I dont set this in my code. Any help is appreciated.
this might help you...
i think response is what you need
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
there was a problem in my defined handle() method. I was creating a new HttpResponse for each request instead of using the response passed in the
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
I am trying to use Google graph API (image) to show some data in the form of PIE chart. http://chart.apis.google.com/chart?chs=250x150&cht=p3&chd=t:41.86,26.00,21.78,10.36&chdl=User998|User591|User671|Others, this link gives a pie chart when viewed in browser. But, when I am trying to get the response using HttpClient, I am getting illegal character error. I am using following code to get the response
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
String chartUrl = "above url";
//Here, I am getting illegal character error.
HttpGet getRequest = new HttpGet(chartUrl);
getRequest.setHeader("Content-Type", "image/png");
httpResponse = client.execute(getRequest);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
bmImg = BitmapFactory.decodeStream(instream);
instream.close();
}
}
catch(Exception e)
{
//TODO
}
Can anyone tell me how to fix this issue?
Thanks,
Ashwani
The character in question is |, you can work around by using %7C instead in the URL and it should work.