I'm attempting to receive a response from a restful service, but receive a timeout. I am able to connect with the browser on my emulator, as I have configured an access point on the emulated device to pass through proxy (at work). Network seems to be fine. I've added:
<uses-permission android:name="android.permission.INTERNET" />
to the AndroidManifest.xml file.
The code is as follows:
public String getInputStreamFromUrl(String url) {
String content = null;
InputStream stream = null;
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
stream = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(stream), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
content = sb.toString();
} catch (Exception e) {
content = e.getMessage();
}
return content;
I know I should return a stream, but for the sake of just displaying some string values in a TextView widget, will suffice, so I'm just using the string to experiment. It consistently hangs on .execute, no matter what URL is passed. I've passed valid IP's as well, with nothin' doin'.
I appreciate your help in advance.
Try this. Put it at the top of the class.
System.setProperty("http.proxyHost", <your proxy host name>);
System.setProperty("http.proxyPort", <your proxy port>);
Related
Guys I may or may not be wrong, But seriously, I am struggling with file uploading problem in Amazon S3 bucket. When I am trying to hit on the request then I am getting the following error.
MethodNotAllowed and The specified method is not allowed against this resource
The above message is the sort of the below response.
<?xml version="1.0" encoding="UTF-8"?><Error><Code>MethodNotAllowed</Code
<Message>Thespecified method is not allowed against this resource.</Message>
<Method>POST</Method><ResourceType>OBJECT</ResourceType>
<RequestId>xxx</RequestId><HostId>xxxx</HostId></Error>
The above message is the complete message and below is the code whatever I have written for uploading files to amazon s3 server.
public synchronized boolean uploadFile(String url, String name, File file) {
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("file", new FileBody(file)).build();
HttpPost request = new HttpPost(url);
request.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
try {
HttpResponse response = client.execute(request);
entity = response.getEntity();
if (entity != null) {
try (InputStream in_stream = entity.getContent()) {
BufferedReader in = new BufferedReader(new InputStreamReader(in_stream));
String inputLine;
StringBuilder responseBuffer = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
responseBuffer.append(inputLine);
}
in.close();
String a = responseBuffer.toString();
Utils.print("\n\n" + a + "\n\n");
}
}
return true;
} catch (Exception e) {
Utils.print(e);
}
return false;
}
Please suggest me what to do for this? I will be very thankful for your expected answer.
You could be getting MethodNotAllowed, which recommends using an identity that belongs to the bucket owner's account.
If you have the correct permissions, but you're not using an identity that belongs to the bucket owner's account, Amazon S3 returns a 405 Method Not Allowed error.
https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketPolicy.html
from a list of S3 API error responses
The specified method is not allowed against this resource.
https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
I am attempting to use Apache HttpClient API to access Atlassian Confluence wiki pages.
Here is my code:
public class ConcfluenceTest{
public static void main(String[] args) {
String pageID = "107544635";
String hostName = "valid_hostname";
String hostScheme = "https";
String username = "verified_username";
String password = "verified_password";
int port = 443;
//set up the username/password authentication
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(hostName, port, AuthScope.ANY_REALM, hostScheme),
new UsernamePasswordCredentials(username, password));
HttpClient client = HttpClientBuilder.create()
.setDefaultCredentialsProvider(credsProvider)
.build();
try {
HttpGet getRequest = new HttpGet("valid_url");
System.out.println(getRequest.toString());
HttpResponse response = client.execute(getRequest);
//Parse the response
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
} catch (UnsupportedEncodingException e) {
System.out.println(e.getStackTrace());
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
}
}
When I attempt to execute this code, the printed response is the HTML of the Log In screen, which means that the authentication failed. This code does, however, return the correct response when I provide it with the URL to a page that is not restricted to registered users (i.e credentials aren't required). I also tried all permutations of port/scheme.
Can someone tell me what I am missing?
Afaik, if http-basic-auth is supported, something like
user:password#server:port/path
should work, too. You could see if that works with a browser.
If Confluence dosen't support basic auth, use firebug to find out the action of the login-form (eg. the path, something like /dologin.action), the method (POST) and the Names of the user/password fields.
With that information you can create a request like this:
HttpPost httpPost = new HttpPost(fullFormActionUrlWithServerAndPort);
List <NameValuePair> nvp = new ArrayList <NameValuePair>();
nvp.add(new BasicNameValuePair("name-of-the-user-field", "your-user-name"));
nvp.add(new BasicNameValuePair("name-of-the-pass-field", "your-password"));
httpPost.setEntity(new UrlEncodedFormEntity(nvp));
I'm trying to remotely deploy application to Tomcat. To do that, I need to do the following GET request:
http://localhost:8080/manager/text/deploy?path=/client-001&war=file:C:/.DS/tmp/client-001.war
I do it from my Java code:
String url = "http://localhost:8080/manager/text/deploy?path=/client-001&war=file:C:/.DS/tmp/client-001.war";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request;
try {
request = new HttpGet(url);
request.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials("test", "test"),
"UTF-8", false));
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.err.println(result.toString());
} catch (Exception e){
e.printStackTrace();
}
but I get 403, even though I've passed my credentials.
What am I doing wrong?
So I found out what the problem was.
1) I didn't need to pass credentials to the Header, I just needed to change url from localhost:8080 to test:test#localhost:8080
2) My user test had role manager-gui, and for GET to work it needed the role manager-script
I've been stuck on this particular dilemma for some time, I have scoured the site and found some help, but not to my particular issue. I'm trying to connect to a website to extract JSON data from it. The host is what i'm not sure about:
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("www.wunderground.com", 80);
HttpGet httpGet = new HttpGet(urllink); // urllink is "api.wunderground.com/api/my_key/conditions/forecast/hourly/alerts/q/32256.json"
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(targetHost, httpGet);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (Exception e) {
// print stacktrace
return null;
} finally {
try {
instream.close();
} catch (Exception e) {
// print stacktrace
return null;
}
}
return stringBuilder.toString();
The host could either be www.wunderground.com or api.wunderground.com, but when I try either of them i get Unknown host exception.
I found the error. It was that I did not have the permission in the android manifest!
The call should be similar to:
http://api.wunderground.com/api/Your_Key/conditions/q/CA/San_Francisco.json
or as stated in the API,
GET http://api.wunderground.com/api/Your_Key/features/settings/q/query.format
I have this code, who should connect to a php remote file and should get a String representing a XML file. But something is wrong, it is giving me error 401.
The variable url is the direction of the php:
String response=getXML("http://ficticiousweb.com/scripts/getMagazinesList.php");
If i paste the real direction (that is a ficticious direction) on the webbrowser, it works and gives me the XML.
This is my code:
public String getXML(String url){
try{
StringBuilder builder = new StringBuilder();
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
int statuscode = response.getStatusLine().getStatusCode();
if(statuscode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) builder.append(line);
}
else throw new Exception("HTTP error: " + String.valueOf(statuscode));
return builder.toString();
}catch(Exception e){e.printStackTrace();}
return null;
}
What is wrong with the code?
thanks
You need to login to the requested site in order to download or access the xml. This can be done by authenticated schema based upon what is supported. Normally, there are 2 types of schemas where used. Basic and Digest. Below code will help you for BASIC AUTH.
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String _username = "username";
String _password = "password";
try {
((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
new org.apache.http.auth.AuthScope(webhostname, webport)),
new org.apache.http.auth.UsernamePasswordCredentials(_username, _password));
response = httpclient.execute(new HttpGet(completeurlhere));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK) {
try {
InputStream is = response.getEntity().getContent();
this._data = is;
} catch(Exception ex) {
Log.e("DBF Error",ex.toString());
}
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch(ClientProtocolException cpe) {
Log.e("ClientProtocolException # at FPT",cpe.toString());
} catch(Exception ex) {
Log.e("Exception at FETCHPROJECTASK",ex.toString());
}
Well a 401 means you aren't Authorized to do the GET request. You should ask the website how to Authenticate the request...
Authorization happens through the Authorization Header in the HTTP request. You should look into that and probably fill that header yourself with your credentials... (if the server accepts that)