How to perform post request in header and body in JSON - java

I'm using JSON and want to send post request to server via username, password in body and x-auth-app-id, x-auth-app-hash in header..
I have test on Postmen and it return 200 (status ok), But when I build my sources it happen error.
This is my class header:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpRequestUtil {
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
InputStream inputStream=null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestProperty("x-auth-app-id", "6166611659356156223");
httpUrlConn.setRequestProperty("x-auth-app-hash", "a44f4ea21475fa6761392ba4bc659990bee771c413b2c207490a79f9ec78c2a61234");
httpUrlConn.setRequestProperty("Content-Type", "application/json");
httpUrlConn.setRequestMethod(requestMethod);
if ("POST".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
}
catch (ConnectException ce) {
ce.printStackTrace();
System.out.println("Our server connection timed out");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("https request error:{}");
}
finally {
try {
if(inputStream!=null) {
inputStream.close();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonObject;
}
}
And class Body:
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class CallCenterController {
public static void main(String[] args) throws JSONException {
String sipUser = "vchi_dd";
String sipPassword = "m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa";
Map<String, Object> sipAccount = new HashMap<String, Object>();
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
sipAccount = postData(sipUser, sipPassword);
System.out.println("result: " + sipAccount);
};
public static JSONObject postData(String sipUser, String sipPassword) {
String url="https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser="+sipUser+"&sipPassword="+sipPassword;
return HttpRequestUtil.httpRequest(url, "POST", "");
}
}
When I build it happen an exception following as:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser=vchi_dd&sipPassword=m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa
https request error:{}
result: null
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.mypackage.HttpRequestUtil.httpRequest(HttpRequestUtil.java:63)
at com.mypackage.CallCenterController.postData(CallCenterController.java:45)
at com.mypackage.CallCenterController.main(CallCenterController.java:34)
How to send correct data to my url and fix the problem?

I would use Java HTTP Client API if your java version is high enough.
Here's a link to it https://www.baeldung.com/java-9-http-client
I have used it and it feels more maintainable and clear.
Also, it seems that you're sending the request with empty body even though you say in your question that you are sending username and password in body.
And why are you adding username and password to a map if you are not using the map?
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);

Related

Java HTTP GET for bearer token?

I'd like to get a bearer token with Java. My API reference says to do a GET with curl:
curl -G "https://api.company.com/api/auth" --data-urlencode "username=<username>" --
data-urlencode "secret=<secret>"
Then, extract the “Value” property or the bearer token from the returned JSON object.
What is the equivalent way to do this with java 8?
Please use something like this:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL url;
try {
url = new URL("https://api.company.com/api/auth?username=<username>&secret=<secret>");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println("Response status: " + status);
System.out.println(content.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Or
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String params = "username=<username>&secret=<secret>";
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://api.company.com/api/auth?" + params);
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response.getStatusLine().getStatusCode());
try {
System.out.println(response.getEntity().getContent());
} catch (IOException e) {
e.printStackTrace();
}
}
}

REST API | Jersey jar | 405 error

I am trying to do automate REST API through Java. For this, I am using Jersy jar.
I googled enough and was able to write a code that doesn't throw any exception. However, I am always getting 405 - Method not allowed error response when I try to reach my project's endpoint and post the request. Same endpoint returns success response on Soap UI. And there are no headers required. Media type is JSON.
Basically, I just want to do the SOAP UI operation, but through Eclipse.
PS: I'm novice, any help is appreciated.
package sample;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import org.glassfish.jersey.client.JerseyInvocation.Builder;
public class Sample
{
public static void main(String a[])
{
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("https://endpoint-url/Resource");
Form form = new Form();
form.param("name", "bond");
form.param("ID", "007");
Builder request = (Builder) resource.request();
request.accept(MediaType.APPLICATION_JSON);
Response response = request.get();
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL)
{
System.out.println("Success! " + response.getStatus());
System.out.println(response.readEntity(String.class));
}
else
{
System.out.println("ERROR! " + response.getStatus());
// System.out.println(response);
System.out.println(response.readEntity(String.class));
}
}
}
The issue at accept,get resource instead of Post resource
you aren't passing form parameter to resource method. That is reason getting issues.Check below
public class Sample {
public static void main(String a[])
{
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("https://endpoint-url/Resource");
Form form = new Form();
form.param("name", "bond");
form.param("ID", "007");
Builder request = (Builder) resource.request();
request.accept(MediaType.APPLICATION_JSON);
Response response = request.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED));
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL)
{
System.out.println("Success! " + response.getStatus());
System.out.println(response.readEntity(String.class));
}
else
{
System.out.println("ERROR! " + response.getStatus()); // System.out.println(response);
System.out.println(response.readEntity(String.class));
}
}
}
Finally, I found the code here that worked wonders for me :)
Below is the working code:
package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class JavaNetURLRESTFulClient
{
private static final String targetURL = "https://endpoint-url/Resource";
public static void main(String[] args)
{
try {
URL targetUrl = new URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");
String input = "{\"name\":\"bond\",\"Id\":007}";
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String output;
System.out.println("Output from Server:\n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

when open connection of URL by Java API it is working fine in development side,but not working on UAT,the error is showing Connection timed out

when open connection of URL by Java API it is working fine in development side,but not working on UAT,the error is showing Connection timed out.Please suggest what to do?
Here given userID,password proxyip and port are not actual because it is the client url.
package qc.los.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import qc.dal.DAL;
import qc.dal.dto.ParameterDTO;
import qc.los.controller.action.NewProspectAction;
import qc.sso.util.UserLockingFilter;
public class Utils {
protected static Logger log = Logger.getLogger(Utils.class);
public static void main(String[] args)
{
Utils Utilss=new Utils();
Utilss.sendVerificationCodeToCustomer("","9811937492","myTestras",true,"properhost","properport");
}
public String sendVerificationCodeToCustomer(String prospectId,String mobileNumber, String verificationCode, boolean proxyEnabled, String proxyHost, String proxyPort)
{
log.info("Start");
Properties systemSettings = System.getProperties();
try
{
//UPdated by for user id password
String urlStr ="http://www.example.com/SendSMS/sendmsg.php?uname=rahul&pass=rahul&send=Tag&dest="+mobileNumber+"&msg=Your%20verification%20code%20is%20"+verificationCode+"&concat=1";
log.info("urlStr "+urlStr);
URL u = new URL (urlStr);
log.info("proxyHost and proxyPort "+proxyHost+" "+proxyPort);
if(proxyEnabled)
{
log.info("proxyEnabled with proxyHost and proxyPort "+proxyHost+" "+proxyPort);
systemSettings.put("proxySet", "true");
systemSettings.put("proxyHost", proxyHost);
systemSettings.put("proxyPort", proxyPort);
}
HttpURLConnection con = (HttpURLConnection) u.openConnection ();
con.setDoInput(true);
con.setRequestMethod("GET");
log.info("Connection start");
con.connect();
log.info("Connection connected");
InputStream is = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null)
{
response.append(line);
response.append("<br>");
}
rd.close();
log.info("End:Message sucessfull with response "+response.toString());
return response.toString();
}
catch(Exception e)
{
String proxySetting = proxyEnabled + ":" + proxyHost + ":" + proxyPort;
e.printStackTrace();
log.error("exception while sending sms:("+proxySetting+")"+" "+e.getMessage());
return "exception while sending sms:("+proxySetting+")"+e.getMessage();
}
finally
{
if(proxyEnabled)
{
systemSettings.remove("proxySet");
systemSettings.remove("proxyHost");
systemSettings.remove("proxyPort");
}
log.info("End");
}
}
}

To write the response of servlet into pdf using httpurlconnection

I am trying to hit a url through URL Connection in servlet. The response of the request (which is a pdf) needs to be displayed on the browser as pdf. Here I do not have any temporary pdf file kept on the server which means i want my code to generate the url response as a pdf on the fly. Currently my webservice returns pdf if I hit the webservice url(REST) directly in the browser.
Here is my code
I am getting a blank output
code:
package com.mm;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\""+ "dummy" + "\"");
byte[] pdfData = servicecall().getBytes("UTF-8");
System.out.println(pdfData.length);
response.setContentLength(pdfData.length);
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.flush();
output.close();
}
public String servicecall()
{
String output = "";
BufferedReader reader = null;
StringBuilder stringBuilder;
try
{
URL url = new URL("http://hardik/Wecs/External/private/document.aspx?prd=1042737~~PDF~~MTR~~IPDS~~EN~~2014-01-10%2014:00:41~~SOLEST%20120~~");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/pdf");
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
reader = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
output = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println( output);
return output;
}
}
I get a blank pdf output

Error in mapper.writeValue() method

I am developing a Java application to be the server in a Google Cloud Messaging Android app.
I have been following a tutorial and I managed to do rest of the tutorial with out a trouble.
My Java application has three classes which are Content.java, POST2GCM.java, App.java. These classes do what the name describes.
Content.java class is below.
package com.hmkcode.vo;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Content implements Serializable {
private List<String> registration_ids;
private Map<String,String> data;
public void addRegId(String regId){
if(registration_ids == null)
registration_ids = new LinkedList<String>();
registration_ids.add(regId);
}
public void createData(String title, String message){
if(data == null)
data = new HashMap<String,String>();
data.put("title", title);
data.put("message", message);
}
}
App.java class is below
package com.hmkcode.vo;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.Content;
public class App
{
public static void main( String[] args )
{
System.out.println( "Sending POST to GCM" );
String apiKey = "AIzaSyB8azikXJKi_NjpWcVNJVO0d........";
Content content = createContent();
POST2GCM.post(apiKey, content);
}
public static Content createContent(){
Content c = new Content();
c.addRegId("APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93....");
c.createData("Test Title", "Test Message");
return c;
}
}
POST2GCM.java class is below
package com.hmkcode.vo;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.*;
public class POST2GCM {
public static void post(String apiKey, Content content){
try{
// 1. URL
URL url = new URL("https://android.googleapis.com/gcm/send");
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. Specify POST method
conn.setRequestMethod("POST");
// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
// 5. Add JSON data into POST request body
//`5.1 Use Jackson object mapper to convert Content object into JSON
ObjectMapper mapper = new ObjectMapper();
// 5.2 Get connection output stream
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
// 5.3 Copy Content "JSON" into
mapper.writeValue(wr,content);
// 5.4 Send the request
wr.flush();
// 5.5 close
wr.close();
// 6. Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 7. Print result
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem arises in the POST2GCM.java class, in the line
mapper.writeValue(wr,content);
Where the suggestions are to add try catch block,Add exception to method signature, Add catch clauses(s).
I did all the suggestions which did not solve the problem.
What would be the problem here?
You need to add the jackson-core-2.4.3.jar library file to your project.
Add it to your java build path too.
Of course ... 2.4.3 is the version I used, but it should work with previous versions.

Categories