How to add header to HttpRequest of GET method in Java - java

I have to pass a token as part of validation for each GET request to access RESTful web service. Below is the code I'm using it to access REST api:
public static String httpGet(String urlStr, String[] paramName, String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
System.out.println("Response code: "+conn.getResponseCode());
throw new IOException(conn.getResponseMessage());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
I can't see any such method to set Header conn.setHeader() provided for HttpsURLConnection. It should be something like X-Cookie: token={token}; please help me to find a way to set header.

You can use:
conn.addRequestProperty("X-Cookie", "token={token}");
or setRequestProperty() also works

You are already setting headers on your request in your code when you do the following:
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
I.e. if the service you are communicating with requires that you send your token in the "X-Cookie" header you can simply do the same for that header:
conn.setRequestProperty("X-Cookie", "token={token}");

Related

How to send JSON data to API using HttpsURLConnection on Android?

How can I send JSON data using HttpsURLConnection to my API ?, this is my code
URL endpoint = new URL("https://api.url.com/api/token/");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("Content-Type", "application/json; utf-8");
myConnection.setRequestProperty("Accept", "application/json");
// Create the data
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
// Enable writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);}
}
I tried this way, but it doesn't work.
Thank you
Send the request:
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try(OutputStream outputStream = conn.getOutputStream()) {
byte[] input = myData.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
To read the response:
StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
}
System.out.println(sb.toString());
I hope that helps!

make an HttpsURLConnection request with parameters by method post

process an https page sending its parameters
Java8u201 using HttpsURLConnection
String httpsURL = "https://www.wmtechnology.org/Consultar-RUC/";
URL myUrl = null;
String[][] parameter = { { "modo", "1" }, { "btnBuscar", "Buscar" }, { "nruc", "10460332759" } };
System.out.println(parameter.toString());
try {
myUrl = new URL(httpsURL);
HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection();
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(parameter.toString());
wr.flush();
wr.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
returns the page but without data
Consider using a library which handles the underlying connection/request for you. The Apache HTTP Client has a fluent API which would make the code easier to write:
String result = Request
.Post("https://www.wmtechnology.org/Consultar-RUC/")
.bodyForm(Form
.form()
.add("modo", "1")
.add("btnBuscar", "Buscar")
.add("nruc", "10460332759")
.build())
.execute()
.returnContent()
.asString();
System.out.println(result);
More information here: https://hc.apache.org/httpcomponents-client-4.2.x/tutorial/html/fluent.html
This request does return data.
You are wrong on the line
wr.writeBytes(parameter.toString());
because parameter.toString() returns string like [[Ljava.lang.String;#1f554b06 instead of expected param1=value1&param2=value2 etc.
So correct this part to
String parameterString = Arrays.stream(parameter)
.map(pair -> pair[0] + "=" + pair[1])
.collect(Collectors.joining("&"));
wr.writeBytes(parameter.toString());

Get the Response from POST request

I would like to obtain the response from a HttpsURLConnection POST request.
If I try to do the request with PostMan, I have one message as response (es: 1520). I have to save this code, but I find the method for read just the getResponseCode() (200) or getResponseMessage() ("OK"). I should use another libraries? Because in the HttpsUrlConnection method I don't find anything useful (https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html)
My code is:
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setSSLSocketFactory(sslContext.getSocketFactory());
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Content-Type", w_AECONTYP);
con.setRequestProperty("Accept-Charset", w_AEACCCHA);
con.setRequestProperty("Accept-Encoding", w_AEACCENC);
StringBuilder postFile = new StringBuilder();
byte[] postFileBytes =w_FileToSend.getBytes("UTF-8");
con.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postFileBytes);
wr.flush();
wr.close();
} catch (Exception e) {
System.out.println("Connection Failed");
e.printStackTrace();
}
int responseCode = con.getResponseCode();
// get 200 code "OK"
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
But when arrived at the WHILE loop, it doesn't enter in the cycle.
How I can do this?
The file is in JSON format, but that isn't the problem.
I need to save that 915 code!!
You could use HttpResponse and HttpPost for getting a response from server (as well as the Response Code):
HttpResponse httpResponse = httpClient.execute(new HttpPost(URL));
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// now response is in the stringBuilder.toString()
I hope this will help you.

Sending JSON request to hipchat

I am making something for my HipChat room but for it to work i have to send a JSON request of:
POST /v1/rooms/message?format=json&auth_token=token HTTP/1.1
Host: api.hipchat.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 138
room_id=10&from=Alerts&message=A+new+user+signed+up
So far i have this:
public static void send(String send){
URL url = null;
HttpURLConnection conn = null;
try{
url = new URL("http://api.hipchat.com");
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", "138");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream ());
wr.writeBytes (send);
wr.flush ();
wr.close ();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(line);
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null) {
conn.disconnect();
}
}
}
But in the console it just returns null. How would i go about sending the above JSON request?
Thanks
Every time you loop here
while((line = rd.readLine()) != null) {
your line variable is replaced with the value returned by rd.readLine(). The last time it loops, that method call will return null. That's why line is null.
I'm going to assume you wanted to print out response.

Http get response utf-8

I have following code. When i get the response, it's characters are faulty. i want to get the response with "UTF-8". How and where can i write that in my code below?
Thanks
URL httpPost = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) httpPost.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.getOutputStream().write(params.getBytes(Charset.forName("UTF-8")));
connection.getOutputStream().flush();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
try {
String responseFromServer = response.toString();
dealsResponse = Utils.mapper.readValue(responseFromServer, GetDealsResponse.class);
} finally {
in.close();
}
connection.setRequestProperty("Accept-Charset", "UTF-8");

Categories