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
Related
In my java code I'm calling third pary apis. In my local workspace it works pretty well and I'm getting proper response. But When I deploy the war in production, I see in logs, I'm calling the apis and didn't get any response. It sound wierd to me and got stuck with it. Please find the snippet and I'm completely calling api in plain old Java.
private void updateRetailerOrderStatus(String trackingId) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
System.out.println("Inside updateRetailerOrderStatus By Android");
Order order = orderDao.getOrdersByTrackingId(trackingId);
HttpPost httpPost = new HttpPost("http://SomeDomine/v1/order/delivered");
httpPost.addHeader("Some Key", "Some Value");
httpPost.addHeader("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("awb_no", order.getTrackingId());
json.put("order_no", order.getOrderId());
json.put("delivered_date", order.getDeliveredDate().toString());
json.put("status", "delivered");
json.put("carrier", "Delivery");
StringEntity entity = new StringEntity(json.toString());
httpPost.setEntity(entity);
System.out.println(json.toString());
HttpResponse response = httpclient.execute(httpPost);
BufferedReader buffReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer respBuffer = new StringBuffer();
String line = "";
while ((line = buffReader.readLine()) != null) {
System.out.println(line);
respBuffer.append(line);
}
System.out.println("API Response: "+ respBuffer.toString());
} catch(Exception ex) {
System.out.println("Error in fetchToken :"+ ex.getMessage());
System.out.println(ex.getStackTrace());
} finally {
try {
httpclient.close();
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
My Questions are:
1) Is there a possibility of happening this? If So, Why?
2) Should I call this in saparate thread? But, I didn't see any suggestions of doing it in most of the examples.
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'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)
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>);