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
Related
I have this code to send JSON data (passed as a string) to the server (This code works when English characters are to be sent as values in dataJSON as far as I tested):
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
Problem is I don't get correct response, which I get for example using DHC Restlet Client.
The problem is I think the dataJSON must be encoded in UTF8. That's how the server expects it most likely.
But it seems I have some problem in code the way I try to convert it and send it.
Can someone help me send data in body as UTF8 string in above example?
I think I solved with this approach:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(dataJSON.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));
in.close();
conn.disconnect();
return result;
}
Please suggest alternative if you see problem with it.
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 currently have code that uses URLEncoder to form a data string that I send to an api.
It url encodes an image on the web.
I want to change it so it url encodes an image on my desktop instead.
How should I go about doing this please? Is there simply a different syntax I need to use, or do I need to parse the path on my desktop so it is readable by URLEncoder?
The code is below. Thankyou for reading
url = new URL("https://api.imgur.com/3/image");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = URLEncoder.encode("image", "UTF-8") + "="
//what i want but doesnt work
+ URLEncoder.encode("C:\\Users\\J\\Desktop\\test5.jpg", "UTF-8");
// what works but i dont want
+ URLEncoder.encode("http://i.imgur.com/FB9OZWQ.jpg", "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Client-ID " + clientID);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.connect();
StringBuilder stb = new StringBuilder();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
The entire class
public class UploadController {
public static String getImgurContent(String clientID) throws Exception {
// clientID = "b290a88ad882073";
URL url;
url = new URL("https://api.imgur.com/3/image");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = URLEncoder.encode("image", "UTF-8") + "="
//what i want but doesnt work
+ URLEncoder.encode("C:\\Users\\J\\Desktop\\test5.jpg", "UTF-8");
// what works but i dont want
+ URLEncoder.encode("http://i.imgur.com/FB9OZWQ.jpg", "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Client-ID " + clientID);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.connect();
StringBuilder stb = new StringBuilder();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
stb.append(line).append("\n");
}
wr.close();
rd.close();
System.out.println(stb.toString());
return stb.toString();
}
}
Thanks to the kind answerer I have updated my code to the follow. I am still getting a 404 however. The base64 looks like this
_9j_4AAQSkZJRgABAQEASABIAAD_2wBDAAYEBQ
The Imgur api should accept it https://api.imgur.com/endpoints/image i think
The code is here:
public class UploadController {
public static String getImgurContent(String clientID) throws Exception {
// clientID = "b290a88ad882073";
URL url;
url = new URL("https://api.imgur.com/3/image");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String file1 = "C:\\Users\\J\\Desktop\\test5.jpg";
// convert to base64
FileInputStream imageInFile = new FileInputStream(file1);
byte imageData[] = new byte[(int) file1.length()];
imageInFile.read(imageData);
String convertedImageData = Base64.encodeBase64URLSafeString(imageData);
System.out.println(convertedImageData);
// String data = "image/png" + "base64" + "=" + convertedImageData;
// sample data string
// data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
// String data = URLEncoder.encode("image", "UTF-8") + "="
//what i want but doesnt work
// + URLEncoder.encode("C:\\Users\\J\\Desktop\\test5.jpg", "UTF-8");
// what works but i dont want
// + URLEncoder.encode("http://i.imgur.com/FB9OZWQ.jpg", "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Client-ID " + clientID);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.connect();
StringBuilder stb = new StringBuilder();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(convertedImageData);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
stb.append(line).append("\n");
}
wr.close();
rd.close();
System.out.println(stb.toString());
return stb.toString();
}
The return message:
Building g5 1.0-SNAPSHOT
------------------------------------------------------------------------
--- exec-maven-plugin:1.2.1:exec (default-cli) # g5 ---
_9j_4AAQSkZJRgABAQEASABIAAD_2wBDAAYEBQ
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.imgur.com/3/image
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1839)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at main.UploadController.getImgurContent(UploadController.java:80)
at main.ImgurMainTest1.main(ImgurMainTest1.java:16)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 2.003s
Finished at: Wed Apr 22 01:17:49 BST 2015
Final Memory: 5M/109M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project g5: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]
To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Just some quick suggestions to avoid any more potentialities:
Change HttpURLConnection to HttpsURLConnection, since you're connecting over SSL but not taking advantage of it.
"image" doesn't need to be URL encoded in the data variable.
You don't need to set the method to POST more than once :p
But for your issue, it's because when you send that GET parametre to the server, the server is interpreting it on its system, not yours. For example, if Imgur's servers were running Windows with a valid directory and file C:\Users\J\Desktop\test5.jpg, the server would use that file instead of your local file. Your issue looks very similar to this one, so try looking at the answer for it. Best of luck. :)
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.
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()));