I'm trying to make a rest request in java. I tested the web service using RestClient in Firefox and it works great.
When i try to modify the HttpsUrlConnection instance in java the values aren't changing and i get a 500 response code.
Here's my code:
public String getAuthToken() throws IOException {
URL url =new URL("https://webserviceurl"); // webservice url is the url of the webservice
String data = URLEncoder.encode("username") + "=" + URLEncoder.encode("myusername","UTF-8");
data+= "&" + URLEncoder.encode("password") + "=" + URLEncoder.encode("pass","UTF-8");
HttpsURLConnection conn =(HttpsURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setHostnameVerifier(new AllowAllHostnameVerifier()); //this works HostName verifier changes
conn.setRequestMethod("POST"); // this doens't work. requestMethod is still set to GET
conn.setDoOutput(true); // this doesnt work. DoOutput still set on false
conn.setRequestProperty("Content-Type", "application/json"); // doens't work either
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
wr.write(data);
wr.flush();
wr.close();
//conn has a 500 response code
if (conn.getResponseCode()==200)
{
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
String token = rd.readLine();
rd.close();
return token;
}
else
return null;
}
I'm stucked at this point and cannot find anything to make this work.
Thank you!
I actually think it's a bug with HttpsURLConnection. As i changed it to a HttpURLConnection object everything works just fine.
Related
I am trying to do what I thought was a simple task. I need to POST data to a PHP server. I have tried this solution but in Apache HttpClient 4.5 I can't find BasicNameValuePair in the package. Upon further research I thought I'd try StringEntity...nope not in 4.5 either (that I can find at least). So I tried to do it with HttpsURLConnection. The problem with that is I can't figure out how to add a name to my parameter and with a name, I don't know how to access in PHP with $_POST['name'].
My Current Code:
String json = gson.toJson(data);
URL url = new URL("https://www.domain.com/test.php");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(json.length()));
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
Try to use DataOutputStream and flush it afterward.
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeChars(json);
wr.flush();
wr.close();
I am calling a REST Web Service with HttpURLConnection like so (this is not the actual URL and credentials, of course I changed the values before posting on a public forum)...
String uri = "http://99.82.36.238:8443/media/crowd?";
String query = String.format("office_code=%s&content_type_code=%s",
URLEncoder.encode("USA"), URLEncoder.encode("SGV"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "text/xml");
String username = "userNewbie";
String password = "password";
conn.setRequestProperty("Authorization", CredentialsEncoder.userNamePasswordBase64(username,password));
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode() + " because " + conn.getResponseMessage());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
The problem is that the service that I am calling does not work in a hand-shake mode. Meaning it needs me to send the creds the first time the request is made, rather than making the request and getting the 403 and then sending the cred.
Can anyone suggest how to modify the above code to meet that requirement?
Thanks.
Here is the code:
String Surl = "http://mysite.com/somefile";
String charset = "UTF-8";
query = String.format("param1=%s¶m2=%s",
URLEncoder.encode("param1", charset),
URLEncoder.encode("param2", charset));
HttpURLConnection urlConnection = (HttpURLConnection) new URL(Surl + "?" + query).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Accept-Charset", charset);
urlConnection.setRequestProperty("User-Agent","<em>Android</em>");
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=" + charset);
urlConnection.connect();
The above still does a GET request. I am using PHP on the server and am able to access the query's 'name=value' params through the $_GET variable and not the $_POST variable
Tested on 2.3.7(device).
What am I missing ?
When you send parameters in the url they are put in the GET variable. You should be posting the parameters in the POST body of the request to achieve what you are looking for. You should add the following just before the connect() call and remove the "?" + query from the url.
urlConnection.setRequestProperty("Content-Length", String.valueOf(query.getBytes().length));
urlConnection.setFixedLengthStreamingMode(query.getBytes().length);
OutputStream output = new BufferedOutputStream(urlConnection.getOutputStream());
output.write(query.getBytes());
output.flush();
output.close();
I'm trying to connect to a webservice using Java and REST. This is what I've tried, and I get a 411 error.
public static String getSiteToken(String host,String token) throws IOException, JSONException
{
host = host.replace("https://", "http://");
URL url = new URL(host + "/tokens");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", token);
conn.setRequestProperty("Content-Length", "57");
//conn.setFixedLengthStreamingMode(57);
conn.setRequestProperty("Connection","keep-alive");
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
JSONObject json = new JSONObject(rd.readLine());
rd.close();
conn.disconnect();
return json.getString("token");
}
I also tried " setFixedLengthStreamingMode " method, but the application wasn't responding after that line of code. Everything works fine when connecting with REST Client for firefox. I can't figure it out. Thanks!
You aren't writing anything to the body of the request. In that case the content length should be 0 and not 57
The program does a http post with basic authorization just fine but when the post is complete the page is redirected to a success page. The redirect failes due to 401 authorization failed.
final URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "basic " +base64);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
The line
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
fails due to 401 authorization failed...
I have also tried adding
conn.setRequestProperty("Authorization", "basic " +base64);
after
wr.flush();
I get the error of "Already connected". Evidently the authorization that I set doesn't follow over to the redirect. Any solutions to this problem is greatly appreciated.
You have 2 options you can try:
Use the setDefaultRequestProperty (see http://download.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html#setDefaultRequestProperty%28java.lang.String,%20java.lang.String%29) method to set the Authorization header.
Disable automatic redirect following: http://download.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html#setInstanceFollowRedirects%28boolean%29 and do it manually.
Here is the working solution for anyone else who has this problem. Thanks again to Femi for providing a workaround idea.
URL url = new URL(page);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "basic " +base64);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
if(conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP){
url = new URL(conn.getHeaderField("Location"));
conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Authorization", "basic " +base64);
}
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));