Response code 500 when accesing rest based web services though eclipse - java

I am trying to invoke a web service from an Eclipse program. But I am getting response code 500 as response. When I access the URL from IE or Mozilla it works fine for me. My sample Eclipse program:
public static void main(String[] args) {
// Use apache commons-httpclient to create the request/response
HttpClient client = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("aaa", "aaaa");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
GetMethod method = new GetMethod("http://localhost:8080/usersByID/2039");
try {
client.executeMethod(method);
InputStream in = method.getResponseBodyAsStream();
// Use dom4j to parse the response and print nicely to the output stream
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
When I opened the link in IE or Mozilla I am getting exact output. The credentials are correct.
Can any one help to overcome this.
Thanks.

Related

Use webservice in Android

I need to send data to a web service that is write in c# .net,
if I use a c# program it can get the names of the web service and
the function that I can use I guess cause it's java it can't do the same
as c#, if someone know how to do this it's will be great.
thanks for the help!
I use httpURLConnection and write this code to send and get the response
from connection.
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + '\n');
}
Log.i("","here "+sb.toString());
return sb.toString();
} catch (Exception e) {
Log.i("","problem in connection");
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If I'm not mistaken, C# web services uses SOAP protocol, so you'll probably need to parse the soap response which will give the information about the web service api:
check this thread:
Parsing SoapObject Responst in android

GET request Tomcat Manager

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

Java:Yahoo contacts API

is there any library or at least some documentation or example on how to import Yahoo! contacts using java and OAuth ?
in my website i need to display/get the yahoo contacts (with oauth)
is there any example.
There is no client library.
You can retrieve contacts in two steps:
Step 1:
Getting 'TOKEN' and 'TOKEN SECRET' of user , using OAuth1. Some libraries are scribe and signpost .
Step 2:
After retrieving these tokens you have to get the yahoo id of the user.
Example: (I am using signpost for this)
OAuthConsumer consumer = new DefaultOAuthConsumer('YOUR CLIENT ID', 'YOUR CLIENT SECRET');
URL url = new URL("http://social.yahooapis.com/v1/me/guid?format=json");
HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
consumer.setTokenWithSecret('TOKEN', 'TOKEN SECRET');
consumer.sign(request1);
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
After this, you have to use the yahoo id of the user retrieved from the user, to get user contacts.
Example:
OAuthConsumer consumer = new DefaultOAuthConsumer('YOUR CLIENT ID', 'YOUR CLIENT SECRET');
URL url = new URL("http://social.yahooapis.com/v1/user/YAHOO_USER_ID/contacts?format=json");
HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
consumer.setTokenWithSecret('TOKEN', 'TOKEN SECRET');
consumer.sign(request1);
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
Method for stream Conversion used above is:
public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}

Using HTTP Post between 2 Java servlets

I have setup a java servlet which accepts parameters from the URL and have it working properly:
public class GetThem extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
try {
double lat=Double.parseDouble(request.getParameter("lat"));
double lon=Double.parseDouble(request.getParameter("lon"));
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(lat + " and " + lon);
} catch (Exception e) {
e.printStackTrace();
}
}
}
So visiting this link:
http://www.example.com:8080/HttpPost/HttpPost?lat=1&lon=2 would output:
"1.0 and 2.0"
I'm currently calling it from another java program using this code:
try{
URL objectGet = new URL("http://www.example.com:8080/HttpPost/HttpPost?lat=" + Double.toString(dg.getLatDouble()) + "&lon=" + Double.toString(dg.getLonDouble()));
URLConnection yc = objectGet.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
...
Now I want to change it so that I'm not using the URL parameters to pass this data to the server. I want to send much larger messages to this server. I am aware that I need to use http post rather than http get to achieve this but am not sure how to do it.
Do I need to change anything on the server side which is receiving data? What do I need to do on the client side which is posting this data?
Any help would be greatly appreciate thanks.
Ideally I'd like to send this data in JSON format.
Below there's sample from the first link found by "java HTTP POST example" in google.
try {
// Construct data
StringBuilder dataBuilder = new StringBuilder();
dataBuilder.append(URLEncoder.encode("key1", "UTF-8")).append('=').append(URLEncoder.encode("value1", "UTF-8")).
append(URLEncoder.encode("key2", "UTF-8")).append('=').append(URLEncoder.encode("value2", "UTF-8"));
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(dataBuilder.toString());
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
I think you should be using HTTPClient instead of handling connections and streams. Check http://hc.apache.org/httpclient-3.x/tutorial.html

Android 2.2 (level 8) httpclient.execute consistent timeout

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>);

Categories

Resources