How to create Atom+xml Post request in Java? - java

This post request is working fine in Postman , when I am try to implement in Java I am getting 400 badrequest , I have tried with spring resttemplate as well Iam getting same error 400 badrequest (Your client has issued a malformed or illegal request)
String url = "PostURL";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Bearer ", token);
con.setRequestProperty("Content-Type",
"application/atom+xml;charset=utf-8");
String urlParameters = "<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:apps='http://schemas.google.com/apps/2006'> <apps:property name=\"publicKey\" value=\"DVNTVJ3ZGoxSjhhR3ZsWVlJQmNrOWYySnNJcEFLZExrb3ljZjRYM0INCk10Y0V2TEp2c1kveFZ2Y2FVNUZ5M2w5NmNLWC9mZGlmU3pacVY0UlN1SDFRQXc9PQ0KPVZBdUENCi0tLS0tRU5EIFBHUCBQVUJMSUMgS0VZIEJMT0NLLS0tLS0=/></atom:entry>";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
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.println("response:" + response.toString());
} catch (IOException e) {
System.out.println("error" + e.getMessage());
Result: I am getting 400 badrequest
Is anything I am missing here??

Related

Is it possible to fill entities on JHipster from an HTTP?

I just started working with JHipster and I created a .jh file with the entities I want. I would like to fill all the entities by doing an HTTP request to an existing HTTP:PORT that already has my needed information.
I would like to know if it's possible? I'm currently trying with this method that I found online:
private static void sendPOST() throws IOException {
// URL obj = new URL(POST_URL);
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("admin", "admin".toCharArray());
}
});
String url = "http://localhost:8080/api/table-simple-tasks";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// HttpURLConnection con = (HttpURLConnection) URL.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.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 request not worked");
}
}

Send GET request with token using Java HttpUrlConnection

I have to work with RESTful web service which uses token-based authentication from Java application. I can successfully get token by this way:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public void getHttpCon() throws Exception{
String POST_PARAMS = "grant_type=password&username=someusrname&password=somepswd&scope=profile";
URL obj = new URL("http://someIP/oauth/token");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Authorization",
"Basic Base64_encoded_clientId:clientSecret");
con.setRequestProperty("Accept",
"application/x-www-form-urlencoded");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.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 request not worked");
}
}
But I cannot find a way to properly send this token in the get request. What I'm trying:
public StringBuffer getSmth(String urlGet, StringBuffer token) throws IOException{
StringBuffer response = null;
URL obj = new URL(urlGet);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
String authString = "Bearer " + Base64.getEncoder().withoutPadding().encodeToString(token.toString().getBytes("utf-8"));
con.setRequestProperty("Authorization", authString);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
System.out.println("GET request not worked");
}
return response;
}
doesn't work. Any help to solve this problem will be highly appreciated.
Solved. Server returns some extra strings besides token itself. All I had to do is to extract pure token from the received answer and paste it without any encoding: String authString = "Bearer " + pure_token;
You should add the token to request url:
String param = "?Authorization=" + token;
URL obj = new URL(urlGet + param);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("GET");
As an alternative, use restTemplate to send a get request:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + token);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(urlGet, HttpMethod.GET, request, String.class);

HttpsURLConnection - Send POST request

I want to send a POST request to this particular API: https://developer.lufthansa.com/docs/read/api_basics/Getting_Started and I researched how to do that and tried everything but it simply doesn't work, I always get an HTTP 400 or an HTTP 401 error. Here's my code:
private void setAccessToken(String clientID, String clientSecret) {
try {
URL url = new URL(URL_BASE + "oauth/token");
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(params);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
Kenta1561
Seems that your code is working well and it may be the case that you are providing invalid clientID or clientSecret so that your are getting wrong response in this case (as 401 indicates unauthorized). One thing you can do is you are only getting the response message if the http request status is ok (200). You may also get the invalid response message in case of 400 or 401 http response status. In order to print the invalid response messages you may follow the code below:
private void setAccessToken(String clientID, String clientSecret) throws Exception {
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
BufferedReader in;
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode >= 400)
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
else
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.println(response.toString());
}
In this way you can also get invalid response message. In your case when I tried to hit the provided api it is giving me the response below:
{"error": "invalid_client"}

While making post call i am getting below exception

Error description:
java.lang.NoSuchMethodError: org.apache.http.HttpHost.getAddress()Ljava/net/InetAddress;
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:102)
Could anyone help me here....what i am missing ???
use below sample code :
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=& num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
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();
//print result
System.out.println(response.toString());
}
}

Retrieve data with HttpUrlConnection even with bad http codes 403. 404, etc

I have the following method that works fine, but it throws an exception when the server returns 403 code which results in the method to never return the server response.
public String ping(String lat, String lon)
{
StringBuffer response = null;
try
{
String url = "https://api.mysite.com";
URL urlObj = new URL(url);
HttpsURLConnection con = null;
if (useProxy)
{
con = (HttpsURLConnection) urlObj.openConnection(proxy);
}
else
{
con = (HttpsURLConnection) urlObj.openConnection();
}
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setRequestProperty("Host", urlObj.getHost());
con.setRequestProperty("Connection", "Keep-Alive");
// con.setRequestProperty("Accept-Encoding", "gzip");
String urlParameters = "{\"lat\":" + lat + ",\"lon\":" + lon + "}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
// System.out.println("\nSending 'POST' request to URL : " + url);
// System.out.println("Post parameters : " + urlParameters);
// System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
return response.toString();
}
How can I make this return the server response no matter what the server returns and even if the server responds with 403 code (or any other response code)?
You only need to add an if block to make the code more robust like below:
public String ping(String lat, String lon)
{
StringBuffer response = null;
try
{
String url = "https://api.mysite.com";
URL urlObj = new URL(url);
HttpsURLConnection con = null;
if (useProxy)
{
con = (HttpsURLConnection) urlObj.openConnection(proxy);
}
else
{
con = (HttpsURLConnection) urlObj.openConnection();
}
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setRequestProperty("Host", urlObj.getHost());
con.setRequestProperty("Connection", "Keep-Alive");
// con.setRequestProperty("Accept-Encoding", "gzip");
String urlParameters = "{\"lat\":" + lat + ",\"lon\":" + lon + "}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
response = readResponse(con.getInputStream());
} else {
response = readResponse(con.getErrorStream());
}
// print result
System.out.println(response.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
return response.toString();
}
private StringBuffer readResponse(InputStream in) {
BufferedReader in = new BufferedReader(new InputStreamReader(in));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
return response;
}
HTH.

Categories

Resources