I try to get string from this url:
http://autoc.finance.yahoo.com/autoc?query=google&callback=YAHOO.Finance.SymbolSuggest.ssCallback
When I look at this in Chrome, I see correct JavaScript responce but when download it from the app with the same headers, I get binary response. How can I get the same correct response in the app?
EDIT:
Code:
public RESTResponse<T> get(String url) {
HttpGet get = new HttpGet(url);
setHeaders(get);
return execute(get);
}
private void setHeaders(HttpRequestBase request) {
request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml");
request.setHeader("Accept-Encoding", "gzip,deflate,sdch");
request.setHeader("Accept-Charset", "UTF-8");
}
private RESTResponse<T> execute(HttpRequestBase request) {
DefaultHttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(request);
return responseFactory.create(response);
} catch (IOException e) {
throw new RuntimeException("Can't perform request.", e);
}
}
hard to tell what's the problem without seeing your code - but you could use that one:
https://github.com/ligi/LigiAndroidCommons/blob/master/src/org/ligi/android/common/net/NetHelper.java
Related
Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed.
Below is my async task background code
HttpClient httpclient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut("URL");
String jsonresponse = "";
try {
StringEntity se = new StringEntity(gson.toJson(resultPojo).toString());
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpPut);
HttpEntity httpEntity = response.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
System.out.println("res .... "+jsonresponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
serverside code :
#POST
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response submitUserResponse(#PathParam("userId") int userId,
#PathParam("id") int id, List<ResultPojo> responses) {
try {
//core logic goes here
return Response.status(Response.Status.CREATED).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
Alright just like what was discussed it is most likely a mismatch different HTTP methods, in this case A Put and a post, whenever you ever encounter that HTTP code(405) do perform a validation on the methods you used, it happens.405 errors often arise with the POST method. You may be trying to introduce some kind of input form on the Web site, but not all ISPs allow the POST method necessary to process the form.A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.
i'm try to get json file from mvc 4 application using webapi
but i get an error in asynctask doinbackground method
java.lang.illegalargumentexception host may not be null
when i track my code i found that it crash on jsonparser in getjson from url at the last line of this code
public JSONObject getJSONFromUrl(String Url) throws JSONException
{
try {
Log.d("tony","6"+Url);
DefaultHttpClient httpClient = new DefaultHttpClient(); // to connect to http
Log.d("tony","7"+Url);
HttpGet httpGet=new HttpGet(Url);
Log.d("tony","8"+httpGet.getMethod());
HttpResponse httpResponse = httpClient.execute(httpGet);
and this is my do in background code
public JSONObject doInBackground(String... urls) {
// get url pointing to entry point of API
String address = urls[0].toString();
if (method.equals(LOAD_REQUEST))
{
return getJSON(address);
}
else
return makeHttpRequest(address, method, parameters);
}
the get json method
public JSONObject getJSON(String url){
JSONObject j = null;
try {
j=parser.getJSONFromUrl(url);
} catch (JSONException e) {
e.printStackTrace();
}
return j;
}
change
localhost:2100/api/products
to
http://localhost:2100/api/products
first correction :
localhost:2100/api/products
to
http://localhost:2100/api/products
Second, change
http://localhost:2100/api/products
to
http://ipaddress:2100/api/products
Because if you are using "localhost" you are pointing to the device host, and you need point the server.
you need to add http:// to the url like that:
http://localhost:2100/api/products
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();
}
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();
}
I am absolutely new to android development and I need help in know how can I invoke a remote servlet which is gonna send me data from a database in the form of xml. I am a beginner and I don't understand jargon. If possible provide me with a link/tutorial for the same.
Any help is greatly appreciated, Thanks!
you need to do this while making a get request.
public boolean funtionAtSite(String sentUrl) {
String url = sentUrl;
HttpGet getMethod = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
try {
ResponseHandler<String> reponseHandler = new BasicResponseHandler();
String responseBody = client.execute(getMethod, reponseHandler);
/******** now do what you want to do with response **********/
if (responseBody.equalsIgnoreCase("1")) {
Log.v(TAG, responseBody);
return true;
}
return false;
} catch (Throwable t) {
return false;
}
}