I am unable to get the response from server when I am making request with http in android. I am calling one url that is working on browser, but default http client request giving me reponse code 500 and response is below. What is missing?
<body>
<h1>Cannot read property '_id' of undefined </h1>
<p>[object Object]</p>
</body>
Here is code
HttpClient httpclient = new DefaultHttpClient();
Log.v("", "url is: "+url);
HttpGet httppost = new HttpGet("http://54.255.228.162:3000/item?action=redeem&event=55018105f0df610b1c3919a2");
try {
org.apache.http.HttpResponse response = httpclient.execute(httppost);
int responsecode = response.getStatusLine().getStatusCode();
result = EntityUtils.toString(response.getEntity());
} catch (Exception ex) {
ex.printStackTrace();
}
Related
I am trying to do a GET request using the foursquare checkin endpoint. I'm getting back a 404 error which is endpoint not found. Any help with why that could be happening would be great!
try {
URI url = new URI("https://api.foursquare.com/v2/user/self/checkins?oauth_token="+TokenStore.get().getToken()+"&v=20140219");
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
is = entity.getContent();
int responceCode = response.getStatusLine().getStatusCode();
Log.i(TAG, "Responce = "+ responceCode);
} catch(Exception e) {
e.printStackTrace();
}
The endpoint is users/self, not user/self, which you have. Just a typo :)
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)
In my application, I am trying to hit a URL which I do using the following code
try {
url = new URL(serverURL);
httpURLConnection = (HttpURLConnection) url.openConnection();
int timeout = 30000;
httpURLConnection.setConnectTimeout(timeout);
httpURLConnection.setReadTimeout(timeout);
httpURLConnection.connect();
String httpResponseMessage = httpURLConnection.getResponseMessage();
responseCode = httpURLConnection.getResponseCode();
Log.i(LOG_TAG,"Response code "+responseCode);
} catch (Exception e) {
e.printStackTrace();
}
The (confidential) URL when opened through browser (on computer as well as on phone), works perfectly and the response is as expected. But when I hit the same URL via the above piece of code, it gives me response code 404 (NOT FOUND). Can anybody tell me what the issue can be?
(Sorry, can not post the URL since is highly confidential.)
Are you sure that you have the android.permission.INTERNET declared in your AndroidManifext.xml?
Problem solved :)
try {
url = new URL(serverURL);
Log.i(LOG_TAG, url+"");
HttpGet method= new HttpGet(new URI(serverURL));
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(serverURL));
HttpResponse response = client.execute(method);
responseCode = response.getStatusLine().getStatusCode();
Log.i(LOG_TAG,"Response code response "+response);
Log.i(LOG_TAG,"Response responseCode "+responseCode);
} catch (Exception e) {
e.printStackTrace();
}
Actually you don't even need following two lines in your code.
HttpGet request = new HttpGet();
request.setURI(new URI(serverURL));
One HttpGet is enough and you don't need it twice.
Not sure if this matters but I had the exact problem.
I was doing some explicity port 80 stuff and removing this line made it work:
HttpHost host = new HttpHost(targetHost, 80, "http");
UPDATE: These problems were caused by a reverse proxy performing a 301 redirect. Altering the url to the destination of the redirect fixed the issue.
I am struggling to make a POST request from android to a web service.
I have a web service running on IIS7 with the following:
<OperationContract()> _
<Web.WebInvoke(BodyStyle:=WebMessageBodyStyle.Bare, Method:="POST", RequestFormat:=WebMessageFormat.Xml, ResponseFormat:=WebMessageFormat.Xml, UriTemplate:="HelloWorld")> _
Function HelloWorld() As XmlElement
When I send a POST request to this url from Firefox it works as expected.
When I make the request from an Android device using the following code:
String sRequest = "http://www.myserviceurl.com/mysevice/HelloWorld";
ArrayList<NameValuePair> arrValues = new ArrayList<NameValuePair>();
arrValues.add(new BasicNameValuePair("hello", "world"));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(sRequest);
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setEntity(new UrlEncodedFormEntity(arrValues));
HttpResponse response = httpClient.execute(httpRequest);
I get a Method Not Allowed 405 response and when looking in the IIS logs the request to this url appears as a "GET".
If I change the target of the request to a PHP script that echoes $_SERVER['REQUEST_METHOD'] the output is POST.
The web.config of the web service has GET, HEAD and POST as verbs.
Is there something I have overlooked?
I had to implement a workaround by disabling the automatic redirect and then catching the response code and redirect URL and reexecuting the POST.
// return false so that no automatic redirect occurrs
httpClient.setRedirectHandler(new DefaultRedirectHandler()
{
#Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context)
{
return false;
}
});
Then when I issued the request
response = httpClient.execute(httpPost, localContext);
int code = response.getStatusLine().getStatusCode();
// if the server responded to the POST with a redirect, get the URL and reexecute the POST
if (code == 302 || code == 301)
{
httpPost.setURI(new URI(response.getHeaders("Location")[0].getValue()));
response = httpClient.execute(httpPost, localContext);
}
try:
DefaultHttpClient http = new DefaultHttpClient();
HttpResponse res;
try {
HttpPost httpost = new HttpPost(s);
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.DEFAULT_CONTENT_CHARSET));
res = http.execute(httpost);
InputStream is = res.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
res = null;
httpost = null;
String ret = new String(baf.toByteArray(),encoding);
return ret;
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
return e.getMessage();
}
catch (IOException e) {
// TODO Auto-generated catch block
return e.getMessage();
}