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");
Related
I have been using this code to get JSON from a specified URL, but today I checked it, and everything in it is deprecated. It still works fine, but I want to know what is the new method of doing it?
Here's what I have:
#Override
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
StringBuilder url = new StringBuilder("some url");
HttpGet hg = new HttpGet(url.toString());
HttpResponse hr = client.execute(hg);
int status = hr.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity he = hr.getEntity();
String data = EntityUtils.toString(he);
jsonGet = new JSONObject(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The deprecated objects are HttpClient, HttpGet, HttpResponse, HttpEntity and EntityUtils.
EDIT: As suggested in some questions, this way
HttpClient client = HttpClientBuilder.create().build();
does not work for me, as I am getting HttpClientBuilder cannot be resolved
Apache httpClient is deprecated with api level 22 you can read it about this blog.
there is a new client for android now and it is very good.
but you can use okhttp instead (also back compat is possible).
EDIT
check this link(URL.openConnection()). this blog was posted in 2011 but they mentioned the deprecation there first as far as i know.
First of all you have to search well on Google.
Here is your answer may it will helps you.
The HttpClient documentation points you in the right direction:
org.apache.http.client.HttpClient:
This interface was deprecated in API level 22.
Please use openConnection() instead. Please visit this webpage for further details.
means that you should switch to java.net.URL.openConnection().
Here's how you could do it:
URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
IOUtils documentation: Apache Commons IO
IOUtils Maven dependency: http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar
Special Thanks to fateddy for this answer
I am trying to send data to my server using HttpPost via the following code.
private boolean FacebookLogin(String url) {
boolean isDataSend = false;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data", FacebookData()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String bufstring = EntityUtils.toString(res.getEntity(),
"UTF-8");
isDataSend = true;
}
} catch (Exception e) {
}
return isDataSend;
}
Is there any way i can have a look at how the $_POST looks on the server end. so that it will be easier for me to code the server part.
You can write the received $_POST on a file. Sometimes I do that. It's not the most elegant solution, but it works fine.
Try using a http proxy (e.g. Fiddler) for debugging, it helps a lot in these cases. You can set up an emulator to use this proxy for network communications, so you can inspect the messages sent and received. Check out the emulator docs on how to configure it to use a proxy.
I'm trying to simulate a process like "cache validation" in my application.
I will download a new version of my webapplication on the device (android-based), but I only want to download a new version of the files, based in a etag comparision.
Does anyone a example of how use the Etag mechanism in Android?
You can access the ETag field from a HttpURLConnection object such as like this:
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
String etag = conn.getHeaderField("ETag");
Of course, you will need to make sure that the server you are testing this against supports ETags.
Maybe class "HttpRequest" from this library (kevinsawicki) will help you.
For example:
File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.body(latest);
//Store eTag of response
String eTag = request.eTag();
//Later you can check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
.ifNoneMatch(eTag)
.notModified();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Response:", response.getFirstHeader("etag").toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can refer to the specific implement of ShallowEtagHeaderFilter performing etag generation and validation in Spring.
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 have to connect to a webserver from android and I have to access a webservice and a webpage from the webserver. Can anybody help me? Please give step by step process with some code snippets because I am new to android and I don't know anything in connecting to a webserver.
You can use an HttpClient:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
HttpResponse httpResponse = httpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
// user reader to read & parse response
reader.close();
Parsing the response obviously depends on the format (e.g. SOAP, JSON, etc.)
You haven't given very much info (what kind of web page, XML/JSON/HTML/etc. ?). But the basic principles of regular Java apply. Using URL and InputStream:
URL url = new URL(...);
InputStream is = url.openStream();
And from there it depends what kind of data you're dealing with.
If you don't want to use an additional library, here is a means for sending an "id" and "name" to a server:
URL url = null;
try {
String registrationUrl = String.format("http://myserver/register?id=%s&name=%s", myId, URLEncoder.encode(myName,"UTF-8"));
url = new URL(registrationUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d("MyApp", "Registration success");
} else {
Log.w("MyApp", "Registration failed for: " + registrationUrl);
}
} catch (Exception ex) {
ex.printStackTrace();
}
You could just as easily send other data via this URI "GET" style, but if you need to send something more detailed a POST will be required.
Note: Originally posted to answer a similar question here: How to connect android to server