Could anyone advise on why this code would not work for a HTTP Post with JSON? No response is received.
I am using Java in Android Studio - using the emulator on my laptop and want to access localhost on my laptop (so using 10.0.2.2).
Then want to take the JSON response, set this as a string just to test I am getting a response.
String jsonResponse = "No response received";
try {
//where write JSON with account details etc
JSONObject json = new JSONObject();
json.put("accountID", "test");
URL url = new URL("http://10.0.2.2:8082/queryTransaction");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.setDoOutput(true);
httpcon.setRequestMethod("POST");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
OutputStreamWriter output = new OutputStreamWriter(httpcon.getOutputStream());
output.write(json.toString());
httpcon.connect();
jsonResponse = httpcon.getResponseMessage();//json response from API
}catch(Exception e){
}
Edit: I get this error which I have now found...
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate com.android.okhttp.HttpUrl$Builder.toString()
so there are a few caveats with this. I got this working after making a few changes.
Make sure to set the charset.
setRequestProperty("charset", "utf-8");
Dont wrap the OutputStream, put it in a try-with-resources, and write the json as a byte array as utf-8 since that what we're accepting.
try (OutputStream output = httpcon.getOutputStream()) {
output.write(json.toString().getBytes(StandardCharsets.UTF_8));
}
Make sure your Json object is correct. If you're going to use accountID make sure you're consuming it properly. Gson/Jackson for example won't be able to parse this as conventionally it would accept account_id or accountId. Use #JsonProperty if needed.
#JsonProperty("account_id")
private final String accountId;
Example Controller with Spring Boot
#RestController
public class TestPostController {
public static class Account {
#JsonProperty("account_id")
private final String accountId;
public Account(String accountId) {
this.accountId = accountId;
}
public Account() {
this(null);
}
public String getAccountId() {
return accountId;
}
}
#PostMapping(path = "/test-post", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Account> response(#RequestBody Account account) {
return ResponseEntity.ok(account);
}
}
Related
I have a requirement to make a post-call to a URL which has OAuth 1.0 authentication. I am pretty new to all these. From my research, I got to know about Scribe in Java, but I can find only Get calls using Scribe. I already have consumerKey and consumerSecret key for OAuth 1.0 authentication. Are there any suggestions on how to achieve this successfully.
With postman I am able to fetch the data successfully, but I want to achieve it using Java.
I have tried something like this
I tried this way
public String getSmartCommPDF(#RequestBody Model model) throws IOException {
OAuthService service = new ServiceBuilder().provider(ModelAPI.class).apiKey(consumerKey)
.apiSecret(consumerSecret).build();
OAuthRequest request = new OAuthRequest(Verb.POST, url);
ObjectMapper mapper = new ObjectMapper();
request.addHeader("Content-Type", "application/json;charset=UTF-8");
request.addPayload(mapper.writeValueAsString(model));
Token accessToken = new Token("", ""); // not required for context.io
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Response = " + response.getBody());
return "Success";
}
This is my ModelAPI class
public class ModelAPI extends DefaultApi10a {
#Override
public String getRequestTokenEndpoint() {
return "https://domain/one/oauth1/api/v6/job";
}
#Override
public String getAccessTokenEndpoint() {
return "https://domain/one/oauth1/api/v6/job";
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return "https://domain/one/oauth1/api/v6/job";
}
}
This part of code is not throwing any error but, the response body is empty. Where I am going wrong, any one has any idea?
Thank you.
The data was coming back in the input stream. So, I used
response.getStream();
and write it to a file and use it.
I have a REST Service an external server like https://api.myrestservice.com and I have a Spring Boot Application running locally on http://localhost:8080. Now I want to make GET or POST request to the REST API address i.e https://api.myrestservice.com/users to get all users, using my locally running Spring Boot App i.e through http://localhost:8080/users. I am not getting how to redirect local app request to external server request.
I hope I got your question right. You are trying get your local app to get data from app running on your server.
You can use the below sample code in your spring boot application.
private void getUsers() {
final String uri = "https://api.myrestservice.com/users";
RestTemplate restTemplate = new RestTemplate();
Users result = restTemplate.getForObject(uri, Users.class);
System.out.println(result);
}
Then your getUsers can be invoked by getUsers Controller in your spring boot app.
I am adding the reference if you want to look at more examples -
https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/
Making post Api call from your code to another server:
suppose you have a server https://searchEmployee... which returns you list of employees belonging to a particular city or belonging to a particular organization:
request body:
{
"city" : "Ranchi",
"organisation" : "Bank Of America"
}
json response: [{"name": "Vikash"},{"name":"kumar" },{}...etc]
Then to make a post api call you can use RestTemplate in java like this:
public void makeApiCall(){
final String uri = "https://searchEmployee...";
RestTemplate restTemplate = new RestTemplate();
String reqBody = "{"city": "Ranchi"}";
String result = restTemplate.postForObject(uri, reqBody, String.class);
// convert your result into json
try {
jsonResponse = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
//extract a value "name" from your json data:
try{
String value = jsonResponse.getString("name");
}catch(JSONException e) {
e.printStackTrace();
}
}
/********************************************************************/
if you have more than one request body parameters to set do it like this:
String reqBody = "{\"quantity\":100,\"name\":\"product1\",\"ifBoolean\":false}";
false is a boolean value here in your request body and 100 is an integer.
NOTE
if you are having problem in setting request body copy it directly from postman request body and paste it inside double quote.
There are many ways to do it. Like Apache HTTP Components and other. Sample
String type = "application/x-www-form-urlencoded" Or Set your desire content type;
String encodedData = URLEncoder.encode( rawData, "UTF-8" );
URL u = new URL("your remote url");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length",
String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());
There are a couple of thing going on here, Like URLEncoding is really mattered when came to security.
Note: Source of above code:here.
This is very Simple By using Java Clients you can Use RestTemplate or UniRest
That one running on Remote is simply Producer and the one which is in local is Consumer So you can exchange method of Resttemplate or get method of Unirest
Example Code is here.
#RequestMapping(value = "/testclient")
public String testclient()
{
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange("https://www.mocky.io/v2/5185415ba171ea3a00704eed", HttpMethod.GET, entity, String.class).getBody();
}
For Unirest code is like this
HttpResponse<JsonNode> jsonResponse = null;
try {
jsonResponse = Unirest.get("https://www.mocky.io/v2/5185415ba171ea3a00704eed")
.header("accept", "application/json").queryString("apiKey", "123").asJson();
} catch (UnirestException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResponse.getBody().toString();
Hey so I'm trying to send some json-object to a rest web service, then get the value of some specific keys, then process the data to finally return a new json-object which is going to be used in another place. Anyway, I'm getting HTTP 204 when I try to communicate with the service.
My rest service looks like this
#Path("/example")
public class PdfMaker {
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response PruebasMet(JSONObject json) throws IOException, JSONException{
try{
String xml = json.getString("xml");
String plantilla = json.getString("plant");
//method that uses "xml" and "plant" and returns "pdf"
JSONObject response = new JSONObject();
response.put("pdf", pdf);
return Response.status(200).entity(pdfb64.toString()).build();
}catch(Exception e){
e.getStackTrace();
return null;
}
}
and I'm trying to communicate with this
public class Jersey {
public static String baseuri = "http://localhost:8080/PdfMakerGF/rest/example/post";
public static void main(String[] args) {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(baseuri);
JSONObject objTest = new JSONobject();
objTest.put("xml","Data1");
objTest.put("plan", "Data2");
ClientResponse res = webResource.header("Content-Type","application/json;charset=UTF-8")
.post(ClientResponse.class, objTest.toString());
System.out.println("output..." + "\n");
System.out.println("Answer "+res);
} catch (Exception e) {
e.printStackTrace();
}
}
But the response that I receive is this one
Answer POST http://localhost:8080/PdfMakerGF/rest/example/post
returned a response status of 204 No Content
Obviously there is something wrong but can't see what is it.
Since I'm stuck with this. Any kind of help would be appreciated.
I'm using netbeans 8.1, Glassfish 4.1 and Jersey.
Thanks
If your server runs into an exception and goes to the catch block, it returns null which corresponds to HTTP 204 (No Content). As sisyphus commented, there should be some exception in the server standard output.
So you probably need to:
Return a different response code (e.g. INTERNAL_SERVER_ERROR or
BAD_REQUEST) in the catch block
Check why the server code is throwing
the exception
Most likely you get an Exception. I guess it is because you have "plant" in one place and "plan" in another.
okey so finaly it works what i need to change was the way that the service was reciving the data, with a inner class in my case, end up working like this ..
Class Aux{
String xml;
String plant;
//generate gettes and setters :)
}
#Path("/example")
public class PdfMaker {
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response PruebasMet(Aux json) throws IOException,
JSONException{
try{
String xml = json.getXml();
String plant = json.getPlant();
//method that uses "xml" and "plant" and returns "pdf"
JSONObject response = new JSONObject();
response.put("pdf", pdf);
return Response.status(200).entity(pdf)).build();
}catch(Exception e){
e.getStackTrace();
return null;
}
}
and the client is ..
Client client = new Client();
WebResource wresource = client.resource("http://localhost:8080/PdfMakerGF/rest/example/post");
JSONObject json = new JSONObject();
json.put("xml", DATA);
json.put("plant", DATA);
ClientResponse response =
wresource.type("application/json").post(ClientResponse.class,
json.toString());
out = response.getEntity(String.class);
System.out.println("RES = "+response);
System.out.println("OUT = "+out);
out has the info that the service is Providing
I have a weird question. I am working on a Java project for work, where we need to make HTTP GET/POST calls to our WEB API. I wanted to make a WebAPI testing project in C#; run it locally (localhost on some random port) and make sure I am sending the right stuff. That way I could control what was sent back(success, errors, JSON, XML, and different variables like that).
Here is some key stuff I have so far:
Client-Java code:
public String sendAPIRequest( HttpRequestMethod method, String apiURI, String payload) throws IOException
{
// Method is GET, POST....
// apiURL specific API navigating to.
// pauload is the html body.
if(payload == null)
{
payload = "";
}
// Establish a connection.
String strURL = String.format("%s%s", this.BaseURL, apiURI);
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Accept-Charset", this.CHARSET);
conn.setRequestMethod(method.toString());
conn.setRequestProperty("Content-Type", "text/json;charset=" + this.CHARSET);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
// write the payload out, if it exists.
//if(payload != null)
{
try(OutputStream output = conn.getOutputStream())
{
output.write(payload.getBytes(CHARSET));
}
}
// read the response.
StringBuilder response = new StringBuilder();
InputStream input = conn.getInputStream();
try(Scanner inputScanner = new Scanner(input))
{
while(inputScanner.hasNextLine())
{
response.append((inputScanner));
}
}
return response.toString();
}
public String CheckForApplicableLicenses(String dCode, String key)
{
String result;
try
{
String APICall = String.format("/license/find_matching?d_code=%s&key=%s", dCode, key);
String Response = API.sendAPIRequest(HttpRequestMethod.GET, APICall);
// TODO Parse the String Response JSON/XMl.
result = Response;
}
catch(Exception ex)
{
// TODO: incorporate some sort of logging and error handling.
result = ex.toString();
}
return result;
}
Server-C#.Net code (tested with fiddler, and in the browser):
[Route("api/[controller]")]
public class LicenseController : Controller
{
[HttpGet]
[Route("find_matching")]
public IEnumerable<string> find_matching(string d_code = "", string key = "")
{
return new string[] { d_code, key };
}
}
Results so far:
I've gotten 404 errors, and I have been able to connect. Most of the time the Java client blows up when I get to the creating the InputStream. I've never been able to trip the breakpoint in the C# server.
Questions:
1) Is what I am doing even feasible? I'm really just trying to test the Java Client, without calling the API, before I am ready. Maybe it has something to do with not running the service on the default HTTP port of 80?
2) Is there a better way of testing this? I don't want to make call to our actual service until we are done.
Thanks in advance for an assistance.
I am trying to get some acquaintance in using facebook API using Java (restfb). I am trying out the following code.
public class FBJava {
private String API_Key = "xxxxxx";
private String API_Secret = "xxxxxxxx";
public String firstReq = "https://graph.facebook.com/oauth/authorize?client_id="+API_Key+"&" +
"redirect_uri=http://www.facebook.com/connect/login_success.html& scope=publish_stream,offline_access,create_event";
public String secondReq = "https://graph.facebook.com/oauth/access_token?client_id="+API_Key+"" +
"&redirect_uri=http://www.facebook.com/connect/login_success.html&client_secret="+API_Secret+"&code=";
public static void main(String[] args) throws IOException {
FBJava fb = new FBJava();
System.out.println(fb.firstReq);
URL request = new URL(fb.firstReq);
HttpURLConnection conn = (HttpURLConnection) request.openConnection();
conn.connect();
int code = conn.getResponseCode();
System.out.println(code);
}
}
When I run the firstReq string in the browser manually, it is redirecting me to the correct page. But when I check the response code I am getting a 400 which means that its a bad request. I want to know why does it respond differently when I try to run it through the program. I know I am doing something wrong, but want to know what is the mistake and why is it occurring? Any kind of insight in this matter would be appreciated.
There is an error in the firstReq url. It contains a whitespace character between "& scope". Try this (I just removed the whitespace):
public String firstReq = "https://graph.facebook.com/oauth/authorize?client_id="+API_Key+"&" +
"redirect_uri=http://www.facebook.com/connect/login_success.html&scope=publish_stream,offline_access,create_event";