I want to know if there is an error response when sending the REST POST request, and i want to print the error as "output" in my Java application.
How do i do this?
Here is the code I'm using:
HttpClient client = new HttpClient();
try {
HttpPost request = new HttpPost("example.com/api/deposit");
StringEntity params;
params = new StringEntity("{"
+ "\"locale\": \"" + exampleclass.getLocale() + "\","
+ "\"dateFormat\": \"" + exampleclass.getDateFormat() + "\","
+ "\"transactionDate\": \"" + exampleclass.getTransactionDate() + "\","
+ "\"transactionAmount\": \"" + exampleclass.getTransactionAmount() + "\","
+ "}");
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept-Language", "en-US,en;q=0.8");
request.addHeader("Authorization", "Basic somecode&&!!");
request.setEntity(params);
HttpResponse response = client.execute(request);
//handle the response somehow
//example : System.out.println (errormessage);
} catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
} finally {
client.getConnectionManager().shutdown();
}
Any help is greatly appreciated!
You should be able to read the returned HTTP status code in the HttpResponse response.
response.getStatusLine().getStatusCode()
return the HTTP code, 200 means OK, another code indicate error.
You can use something as below:-
String line = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(getResponse.getEntity().getContent()));
while ((line = rd.readLine()) != null)
{
System.out.println(line);
}
Related
I am creating a Java Rest api to create users on Google Duo admin. I am following the documentation https://duo.com/docs/adminapi and I have added auth and date/time header but still I am getting unauthorised error 401. Can anyone guide me what am I doing wrong I have read the doc and added all the mandatory headers.
public static void POSTRequest() throws IOException {
String userCredentials = "Username:Password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" +
" \"id\": 101,\r\n" +
" \"title\": \"Test Title\",\r\n" +
" \"body\": \"Test Body\"" + "\n}";
URL obj = new URL("https://api-e9770554.duosecurity.com");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setRequestProperty("Authorization", basicAuth);
postConnection.setRequestProperty("Date", dateTime);
postConnection.setDoOutput(true);
OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST NOT WORKED");
}
}
Error:
{
"code": 40101,
"message": "Missing request credentials",
"stat": "FAIL"
}
Response code: 401 (Unauthorized); Time: 2022ms; Content length: 73 bytes
I want to send this request through my java code:
curl -u "user:key" -X PUT -H "Content-Type: application/json" -d "{"status":"test", "reason":"test"}" https://test.com/test/id.json
I've tried using Runtime:
String command =
"curl -u \"" + user + ":" + key + "\" -X PUT -H \"Content-Type: application/json\" -d \""
+ "{\\\"status\\\":\\\"test\\\","
+ "\\\"reason\\\":\\\"test\\\"}\" "
+ urlString + jsonID + ".json";
Runtime.getRuntime().exec(command);
I've also tried ProcessBuilder:
String[] command2 = {"curl", "-u", "\"" + user + ":" + key + "\"", "-X", "PUT", "-H", "\"Content-Type: application/json\"", "-d",
"\"{\\\"status\\\":\\\"test\\\",\\\"reason\\\":\\\"test\\\"}\"",
urlString + jsonID + ".json"};
Process proc = new ProcessBuilder(command2).start();
And finally with Apache HttpClient
credsProvider.setCredentials(new AuthScope("test.com", 80), new UsernamePasswordCredentials(user, key));
HttpClientBuilder clientbuilder = HttpClients.custom();
clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);
CloseableHttpClient httpClient = clientbuilder.build();
HttpPut put = new HttpPut(urlString + jsonID + ".json");
put.setHeader("Content-type", "application/json");
String inputJson = "{\n" +
" \"status\": \"test\",\n" +
" \"reason\": \"test\"\n" +
"}";
try {
StringEntity stringEntity = new StringEntity(inputJson);
put.setEntity(stringEntity);
System.out.println("Executing request " + put.getRequestLine());
HttpResponse response = null;
response = httpClient.execute(put);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
StringBuffer result = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
System.out.println("Response : \n"+result.append(line));
}
} catch (UnsupportedEncodingException e1) {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Runtime and ProcessBuilders didn't return any results, but Apache HttpClient returned an Error 401 even though my credentials are correct. If I were to copy the command string and enter it into terminal, it would give a valid response.
Any help please? I've been on this for hours :(
Finally got it working
String host = //use your same url but replace the https:// with www
String uriString = String.format("https://%s:%s#%s%s.json", user, key, host, jsonID);
Log.debug("Sending PUT request to URI: {}\n\n", uriString);
try {
URI uri = new URI(uriString);
HttpPut putRequest = new HttpPut(uri);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add((new BasicNameValuePair("status", status)));
nameValuePairs.add((new BasicNameValuePair("reason", "TEST " + status.toUpperCase())));
putRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = HttpClientBuilder.create().build().execute(putRequest);
System.out.println("\n");
Log.debug("Retrieving API response");
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
StringBuffer result = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
Log.debug("Response : \n{}", result.append(line));
}
}
Hope this helps anyone looking for a similar solution in the future. Again this is for a curl request that looks like this:
curl -u "user:key" -X PUT -H "Content-Type: application/json" -d "{"key":"value", "key2":"value2"}" https://test.com/test/id.json
I want to use the MailChimp api to add a subscriber. As a start, want to read from one of the REST I'm trying to get a response back from the MailChimp api.
I seem to be doing the authorization correctly as I'm getting status 200, but for some reason, I am not getting the response.
Here is the code so far:
public void doPostAction() throws IOException{
// BASIC Authentication
String name = "user";
String password = apikey;
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL urlConnector = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) urlConnector.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = httpConnection.getInputStream();
// check status
System.out.println("DoPost: status: " + httpConnection.getResponseCode());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println("DoPost response: \n" + line);
br.close();
}
Looking at the MailChimp playground, it seems like I'm missing out on a lot...
How do I get the response?
****/ EDIT /****
If anyone's looking at the above code, the output should be:
System.out.println("DoPost response: \n" + sb); // not line
OK, the above code works. Basic error.
I was examining the line variable when it was null, not the response...
When I change to:
System.out.println("DoPost response: \n" + line); // not line
System.out.println("DoPost response: \n" + sb); // but sb StringBuilder
...it works.
I'm trying to set the OAuth Authorization header of a HttpsURLConnection object and below is the java code for that
String url1 = "/data/ServiceAccount?schema=1.0&form=json&byBillingAccountId={EQUALS,xyz#pqr.edu}";
String url = "https://secure.api.abc.net/data/ServiceAccount?schema=1.0&byBillingAccountId={EQUALS,xyz#pqr.edu}";
String header = OAuthClient.prepareURLWithOAuthSignature(url1);
HttpsURLConnection con = null;
try {
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "OAuth " + header);
System.out.println("Request properties = " + con.getRequestProperty("Authorization"));
int responseCode = con.getResponseCode();
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();
con.disconnect();
//print result
System.out.println("Response = " + response.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(con!=null) con.disconnect();
}
And below is the code for prepareURLWithOAuthSignature
public String prepareURLWithOAuthSignature(String url)
{
String signature = null;
setOAuthParameters();
setOAuthQParams();
try
{
httpURL = URLEncoder.encode(baseURL+url, "UTF-8");
signature = OAuthSignatureService.getSignature(httpURL, URLEncoder.encode(URLEncodedUtils.format(qparams, "UTF-8"), "UTF-8"), consumer_secret);
OAuthParameters.put("oauth_signature", signature);
} catch (Exception e) {
e.printStackTrace();
}
return getOAuthAuthorizationHeader();
}
public String getOAuthAuthorizationHeader()
{
String OAuthHeader = "oauth_consumer_key=\"" + OAuthParameters.get("oauth_consumer_key") + "\"" +
",oauth_signature_method=\"" + OAuthParameters.get("oauth_signature_method") + "\"" +
",oauth_timestamp=\"" + OAuthParameters.get("oauth_timestamp") + "\"" +
",oauth_nonce=\"" + OAuthParameters.get("oauth_nonce") + "\"" +
",oauth_version=\"" + OAuthParameters.get("oauth_version") + "\"" +
",oauth_signature=\"" + OAuthParameters.get("oauth_signature") + "\"";
byte[] authEncBytes = Base64.encodeBase64(OAuthHeader.getBytes());
String authStringEnc = new String(authEncBytes);
return authStringEnc;
}
The problem is that
1) while I'm printing the con.getRequestProperty("Authorization") I'm getting a null value which means the Authorization header is not set
2) The final response I'm getting from the server is 403
Any idea what's going wrong here?
I know this might not be an answer but looks like this issue was submitted as a bug to sun and here is the relevant part of the reply.
This behavior is intentional in order to prevent a security hole that
getRequestProperty() opened. setRequestProperty("Authorization")
should still work, you just won't be able to proof the results via
getRequestProperty().
For the original forum post, please see: http://www.coderanch.com/t/205485/sockets/java/setRequestProperty-authorization-JDK
I would not be able to advice why you're getting a 403 but try adding the "Content-Type" request header to your connection and see if it makes any difference. Until I added that header in my code, I was getting a 404 back from the Spring Security module.
I have a java servlet class that is performing a GET to a specific URL. I am also passing data as part of the GET.
What I need, is in my HTTP Server code that recieves this data, how do I insert user based response data into the Header back so my calling Java servlet class can read it.
I can read standard response things like .getResponseCode() etc, but I need to insert my own response into the header some how. How can this be done? and how can I read it?
This is my java servlet send class:
public void sendRequest(String data, String sendUrl) throws Throwable{
String messageEncoded = URLEncoder.encode(data, "UTF-8");
String message = URLDecoder.decode(messageEncoded);
System.out.println("messageEncoded : " + messageEncoded);
System.out.println("messageDecoded : " + message);
try {
URL url = new URL(sendUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(message);
writer.close();
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
System.out.println(" *** headers ***");
for (Entry<String, List<String>> headernew : connection.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
}
System.out.println(" \n\n*** Body ***");
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println("body=" + sb.toString());
System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Ok
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
System.out.println(this.getClass() + " : MalformedURLException Error occured due to: " + e);
} catch (IOException e) {
System.out.println(this.getClass() + " : IOException Error occured due to: " + e);
}
}