Java - HttpURLConnection - How to insert user data into Header Response - java

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

Related

I want to create a user on Google Duo through Java Rest api. Followed documentation but getting error

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

How tu use PerspectiveAPI in Java?

how to use the perspective api, in java, I have tried several codes and it does not work too much .
I have do this, but not work.
`
try {
String url = "https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1&", key = "key=my_key";
final URL serverUrl = new URL(url + key);
URLConnection urlConnection = serverUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)urlConnection;
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setDoOutput(true);
BufferedWriter httpRequestBodyWriter = new BufferedWriter(new
OutputStreamWriter(httpConnection.getOutputStream()));
httpRequestBodyWriter.write("{\"comment\": {\"text\": \"" + "Salut mec" + "\"},"
+ "\"requestedAttributes\": {\"TOXICITY\": {}}}");
httpRequestBodyWriter.flush();
httpRequestBodyWriter.close();
System.out.println("CODE : " + httpConnection.getResponseCode());
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));
String output;
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}`
I have Code 404, and Caused by: java.io.FileNotFoundException: https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1&key=my_key
Have you an idea ?

How to implement HTTP POST method in web proxy through Java

I am trying to make a web proxy for HTTP communication between server and client. The GET method is working fine but I am POST method part is not working. I am sure I have missed out something. I want to know what have I missed or not implemented.
// request from client is handle from here
while ((inputLine = in.readLine()) != null) {
try {
StringTokenizer tok = new StringTokenizer(inputLine);
tok.nextToken();
} catch (Exception e) {
break;
}
if (cnt == 0) {
System.out.println("inputLine "+inputLine);
String[] tokens = inputLine.split(" ");
urlToCall = tokens[1];
//hum inputline sy URL nikaal rahay hai
if(tokens[0]=="POST")
{
f=1;
}
System.out.println("Request for : " + urlToCall);
}
cnt++;
}
BufferedReader rd = null;
try {
//yaha sy hum ab server ko request send karay gy
URL url = new URL(urlToCall);
URLConnection conn = url.openConnection();
HttpURLConnection huc = (HttpURLConnection) conn;
conn.setDoInput(true);
conn.setDoOutput(false);
// now we will get the response from the server
if (f == 1) {
huc.setDoOutput(true);
huc.setInstanceFollowRedirects(false);
huc.setRequestMethod("POST");
huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
huc.setRequestProperty("charset", "utf-8");
}
InputStream is = null;
if (conn.getContentLength() > 0)
{
try {
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
} catch (IOException ioe) {
System.out.println(
"********* IO EXCEPTION **********: " + ioe);
}
}
What is the error you are getting on the post? And what is a sample GET request that is being passed into your code?
When I use a simple GET request, the code fails because the urlToCall does not have the host or protocol. The below code worked for me, but I would highly suggest you change your code to not hide the exceptions that are being thrown because they will have important information about what is going wrong with your code.
if (cnt == 1) {
System.out.println("host: " + inputLine);
String[] tokens = inputLine.split(" ");
urlToCall = "HTTP://" + tokens[1] + urlToCall;
}

How to make HTTP POST request using JSON?

I understand Java but am completely inexperienced with connecting to web applications. How would I take the following HTTP POST request and make it JSON? The overall purpose is to send information from a Java application to an online Ruby on Rails SQLite3 database.
import java.io.*;
import java.net.*;
public class HTTPPostRequestWithSocket {
public void sendRequest() {
try {
String params = URLEncoder.encode("param1", "UTF-8") + "="
+ URLEncoder.encode("value1", "UTF-8");
params += "&" + URLEncoder.encode("param2", "UTF-8") + "="
+ URLEncoder.encode("value2", "UTF-8");
String hostname = "nameofthewebsite.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
String path = "/nameofapp";
// Send headers
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "UTF8"));
wr.write("POST " + path + " HTTP/1.0rn");
wr.write("Content-Length: " + params.length() + "rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
socket.close(); // Should this be closed at this point?
} catch (Exception e) {
e.printStackTrace();
}
}
}

Unable to set Authorization header of HttpsURLConnection

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.

Categories