Rectangle 27 4

-d x=1&y=2 (notice the =, not :) is form data (application/x-www-form-urlencoded) sent it the body of the request, in which your resource method should look more like

@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String sumPost(@FormParam("x") int x,
                      @FormParam("y") int y) {

}

and the following request would work

curl -XPOST "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -d 'x=5&y=3'
"x=5&y=3"

You could even separate the key value pairs

curl -XPOST "http://localhost:8080/..." -d 'x=5' -d 'y=3'
Content-Type
application/x-www-form-urlencoded

@QueryParams are supposed to be part of the query string (part of the URL), not part of the body data. So your request should be more like

curl "http://localhost:8080/CurlServer/curl/curltutorial/sumPost?x=1&y=2"

With this though, since you are not sending any data in the body, you should probably just make the resource method a GET method.

@GET
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
public String sumPost(@QueryParam("x") int x,
                      @QueryParam("y") int y) {
}

If you wanted to send JSON, then your best bet is to make sure you have a JSON provider[1] that handle deserializing to a POJO. Then you can have something like

public class Operands {
    private int x;
    private int y;
    // getX setX getY setY
}
...
@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String sumPost(Operands ops) {

}

[1]- The important thing is that you do have a JSON provider. If you don't have one, you will get an exception with a message like "No MessageBodyReader found for mediatype application/json and type Operands". I would need to know what Jersey version and if you are using Maven or not, to able to determine how you should add JSON support. But for general information you can see

since you are not sending any data in the body, you should probably just make the resource method a GET method.

Maybe what I should've said is "since the resource method is not expecting any data in the body". You have no method parameters to accept a body. Generally a method argument to accept a body has no annotations. In most cases that is how it is known to be the entity body (the exception to the case being form data). In your case the data is expected to come in the URL (@QueryParam)

okay it is obvious that i made a mistake using queryparam, i didn't know that queryparam is for url. but if i change it to form param will that mean that the x and y are in the body of the http request ?

Yes. And with -d, that sends it in the body. Then the first example is what you would go with.

do I understand that -d '{"x":3, "y":4}' doesn't mean that the request is json? plus one for now

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - URL parameters are not being passed by curl POST - Stack Overfl...

java curl jersey http-post
Rectangle 27 4

-d x=1&y=2 (notice the =, not :) is form data (application/x-www-form-urlencoded) sent it the body of the request, in which your resource method should look more like

@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String sumPost(@FormParam("x") int x,
                      @FormParam("y") int y) {

}

and the following request would work

curl -XPOST "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -d 'x=5&y=3'
"x=5&y=3"

You could even separate the key value pairs

curl -XPOST "http://localhost:8080/..." -d 'x=5' -d 'y=3'
Content-Type
application/x-www-form-urlencoded

@QueryParams are supposed to be part of the query string (part of the URL), not part of the body data. So your request should be more like

curl "http://localhost:8080/CurlServer/curl/curltutorial/sumPost?x=1&y=2"

With this though, since you are not sending any data in the body, you should probably just make the resource method a GET method.

@GET
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
public String sumPost(@QueryParam("x") int x,
                      @QueryParam("y") int y) {
}

If you wanted to send JSON, then your best bet is to make sure you have a JSON provider[1] that handle deserializing to a POJO. Then you can have something like

public class Operands {
    private int x;
    private int y;
    // getX setX getY setY
}
...
@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String sumPost(Operands ops) {

}

[1]- The important thing is that you do have a JSON provider. If you don't have one, you will get an exception with a message like "No MessageBodyReader found for mediatype application/json and type Operands". I would need to know what Jersey version and if you are using Maven or not, to able to determine how you should add JSON support. But for general information you can see

since you are not sending any data in the body, you should probably just make the resource method a GET method.

Maybe what I should've said is "since the resource method is not expecting any data in the body". You have no method parameters to accept a body. Generally a method argument to accept a body has no annotations. In most cases that is how it is known to be the entity body (the exception to the case being form data). In your case the data is expected to come in the URL (@QueryParam)

okay it is obvious that i made a mistake using queryparam, i didn't know that queryparam is for url. but if i change it to form param will that mean that the x and y are in the body of the http request ?

Yes. And with -d, that sends it in the body. Then the first example is what you would go with.

do I understand that -d '{"x":3, "y":4}' doesn't mean that the request is json? plus one for now

java - URL parameters are not being passed by curl POST - Stack Overfl...

java curl jersey http-post
Rectangle 27 6

Answer 1: You can automate the creation of OAuth Consumers, but you probably dont want to.

Bitbucket provides documentation on how to create a consumer through their APIs, although the documentation is lacking many pertinent fields. Even so, you could still craft an HTTP request programmatically which mimics whatever Bitbucket's web interface is doing to create consumers. So yes, it could be automated.

Here's why you probably don't want to. In your case, you have three things that need to work together: your application, the end user, and Bitbucket. (Or in terms of OAuth jargon for this flow, those would be the client, resource owner, and authorization server, respectively.) The normal way of doing things is that your application is uniquely identified by the OAuth Consumer that youve created in your account, and all usages of Bitbucket by your application will use that single OAuth Consumer to identify your application. So unless youre doing something like developing a Bitbucket application that generates other Bitbucket applications, you have no need to automate the creation of other OAuth Consumers.

Answer 2: You can authorize directly from your Java application.

Bitbucket states that it supports all four grant flows/types defined in RFC-6749. Your code is currently trying to use the Authorization Code Grant type. Using this grant type WILL force you to use a browser. But thats not the only problem with this grant type for a desktop application. Without a public webserver to point at, you will have to use localhost in your callback URL, as you are already doing. That is a big security hole because malicious software could intercept traffic to your callback URL to gain access to tokens that the end user is granting to your application only. (See the comments on this stackoverflow question for more discussion on that topic.) Instead, you should be using the Resource Owner Password Credentials Grant type which will allow you to authenticate a Bitbuckets username and password directly in your application, without the need of an external browser or a callback URL. Bitbucket provides a sample curl command on how to use that grant type here.

Answer 3: The correct next steps would be to model your code after the following sample. What is wrong with your approach is that you are trying to use a grant type that is ill-suited to your needs, and you are attempting to use your OAuth Consumer's name to identify your application instead of your Consumer's key and secret.

The following code sample successfully retrieved an access token with my own username/password/key/secret combination, whose values have been substituted out. Code was tested using JDK 1.8.0_45 and org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0.

OAuthClientRequest request = OAuthClientRequest
    .tokenLocation("https://bitbucket.org/site/oauth2/access_token")
    .setGrantType(GrantType.PASSWORD)
    .setUsername("someUsernameEnteredByEndUser")
    .setPassword("somePasswordEnteredByEndUser")
    .buildBodyMessage();
String key = "yourConsumerKey";
String secret = "yourConsumerSecret";
byte[] unencodedConsumerAuth = (key + ":" + secret).getBytes(StandardCharsets.UTF_8);
byte[] encodedConsumerAuth = Base64.getEncoder().encode(unencodedConsumerAuth);
request.setHeader("Authorization", "Basic " + new String(encodedConsumerAuth, StandardCharsets.UTF_8));
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse response = oAuthClient.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
System.out.println("response body: " + response.getBody());

Thank you for this very detailed answer. I didn't try it yet, but I guessed already, that chose the wrong authentication type. The bounty goes to you!

You were very much helpfull i ate all the google to know from where to get the authrization header value, only now i know it is base64....'

oauth 2.0 - How to access Bitbucket API from a Java Desktop App via Je...

java oauth-2.0 bitbucket-api oltu
Rectangle 27 1

A simple, but not pure java solution, is to shell out to curl from java, which gives you complete control over how the request is done. If you're just doing this for something simple, this allows you to ignore certificate errors at times, by using this method. This example shows how to make a request against a secure server with a valid or invalid certificate, pass in a cookie, and get the output using curl from java.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class MyTestClass
{
  public static void main(String[] args) 
  {
    String url = "https://www.google.com";
    String sessionId = "faf419e0-45a5-47b3-96d1-8c62b2a3b558";

    // Curl options are:
    // -k: ignore certificate errors
    // -L: follow redirects
    // -s: non verbose
    // -H: add a http header

    String[] command = { "curl", "-k", "-L", "-s", "-H", "Cookie: MYSESSIONCOOKIENAME=" + sessionId + ";", "-H", "Accept:*/*", url };
    String output = executeShellCmd(command, "/tmp", true, true);
    System.out.println(output);
  }

  public String executeShellCmd(String[] command, String workingFolder, boolean wantsOutput, boolean wantsErrors)
  {
    try
    {
      ProcessBuilder pb = new ProcessBuilder(command);
      File wf = new File(workingFolder);
      pb.directory(wf);

      Process proc = pb.start();
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

      StringBuffer sb = new StringBuffer();
      String newLine = System.getProperty("line.separator");
      String s;

      // read stdout from the command
      if (wantsOutput)
      {
        while ((s = stdInput.readLine()) != null)
        {
          sb.append(s);
          sb.append(newLine);
        }
      }

      // read any errors from the attempted command
      if (wantsErrors)
      {
        while ((s = stdError.readLine()) != null)
        {
          sb.append(s);
          sb.append(newLine);
        }
      }

      String result = sb.toString();

      return result;
    }
    catch (IOException e)
    {
      throw new RuntimeException("Problem occurred:", e);
    }
  }


}

ssl - Java and HTTPS url connection without downloading certificate - ...

java ssl https
Rectangle 27 0

'Curl' is just a library that is used to make HTTP requests in php. In android(java) you can achieve the same using the HttpURLConnection class. You can add your authentication string as a request property. Following example may help:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String oAuth = "Basic " + new String(new Base64().encode("oath authentication string"));
myURLConnection.setRequestProperty ("Authorization", oAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
//open the connection and write to the output stream & then read from input stream.

How to use the curl in android Twitter integration - Stack Overflow

android twitter twitter-oauth
Rectangle 27 0

HttpClient enabled compression by default and the OANDA API does not support ETags when compression is enabled:

Note: ETags can not be used in conjunction with compressed responses.

http - Why does response to my Java GET request have fewer headers tha...

java http
Rectangle 27 0

A general tip first: use for instance FireFox with the TamperData add-on, which enables to trace a regular form submit, and inspect everything. In your case a proxy monitor might be more of a help. Also:

curl --trace-ascii ...

Without encoding parameter the current platform encoding is taken; non-portable.

OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream(),
        StandardCharsets.UTF_8);
Reader in = new BufferedReader(new InputStreamReader(
        connection.getInputStream(),
        StandardCharsets.UTF_8));

HTTP POST request to JIRA using Java yields 400 bad request error, cur...

java http post jira jira-rest-api
Rectangle 27 0

You seem to have extra single quotes in the post data.

String data = "'{\"jql\":\"project = PROJ\"}'";
String data = "{\"jql\":\"project = PROJ\"}";

Incidentally, even though you are getting a 400 Bad Request, JIRA is still providing useful information that helps localize the error. You can look at it using the connection's getErrorStream method. If we quickly slap this onto your code:

import java.io.*;
import java.net.*;
import java.util.*;

public class JiraConnector 
{
    public static void main(String[] args)
    {
        HttpURLConnection connection = null;
        try {
            //store necessary query information
            URL jiraURL = new URL("http://127.0.0.1:8082/rest/api/2/search");
            String data = "{\"jql\":\"project = PROJ\"}";

            //establish connection and request properties
            connection = (HttpURLConnection)jiraURL.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);

            connection.connect();

            OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
            wr.write(data.toString());
            wr.flush();
            wr.close();

            Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            for (int c; (c = in.read()) >= 0; System.out.print((char)c));

        } catch (MalformedURLException e) {
            System.err.println("MalformedURLException: " + e.getMessage());
        } catch (java.net.UnknownServiceException e) {
            System.err.println("UnknownServiceException: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
            if (connection != null) {
                try {
                    System.out.println(connection.getResponseMessage());

                    InputStream errorStream = connection.getErrorStream();
                    if (errorStream != null) {
                        Reader in = new BufferedReader(new InputStreamReader(errorStream));
                        for (int c; (c = in.read()) >= 0; System.out.print((char)c));
                    }
                }
                catch (IOException e2) {
                }
            }
        }        
    }
}

If you're going to be doing any serious work against the REST API, I would recommend looking at using Jersey instead of trying to roll your own.

HTTP POST request to JIRA using Java yields 400 bad request error, cur...

java http post jira jira-rest-api
Rectangle 27 0

Don't know about mockMVC, but if this gets rendered in an HTML page, you could use the Chrome developer tools to generate the curl statement for you.

Start Tools/Developer Tools, click the network tab, click the link/button/thing that causes the request, find the request in the Network tab, right click, copy as cUrl.

Obviously, if it's not rendered in an HTML page, this isn't going to be a great deal of help.

Thanks. Its not in an HTML page but this is good to know.

java - MockMvc show corresponding curl command or http request - Stack...

java api spring-mvc curl
Rectangle 27 0

(I'm assuming you are using exactly the same URL in the browser and using curl ...)

If the browser is running on a different host to the service, then the reason is that localhost IP addresses (e.g. 127.0.0.1) are not routed to any other hosts apart from the host they were sent from. (That's what "local" means ...) In short, this is normal behaviour. (And maybe you are running curl and the browser on different hosts.)

If the browser is running on the same host as the service, this behaviour is a bit puzzling. However there are some possible explanations:

java - Why can't I connect to http server on localhost through a brows...

java http browser curl request
Rectangle 27 0

I'm not sure whether HttpURLConnection is your best friend here. I think Apache HttpClient is a better option here.

Just in case you must use HttpURLConnection, you can try this links:

You are setting username/password, a HTTP-Header option and ignore SSL certificate validation.

Thanks a lot for the links; very helpful.

Converting CURL request to HTTP Request Java - Stack Overflow

java curl
Rectangle 27 0

I don't know what this has to do with a database, but --digest turns on Digest authentication. Without it you are using Basic authentication.

Here's the canonical reference for what those both mean, I'll look to see if I can find something a little more reader friendly and add it if I do.

This seems a little easer to... well... --digest :)

And I also reccomend Apache HTTP client for doing http requests from java, though I'm not sure from your question intro where you mention databases if that's actually what you want to do.

Thanks. Database was a bad choice of words. I am trying to connect to a server that has a database on it.

curl - setting up a digest http request with a java library - Stack Ov...

java curl http-headers digest digest-authentication
Rectangle 27 0

The headers don't match. The curl command is using X-Parse-Application-Id and X-Parse-REST-API-Key whereas the Java code is using Example-Application-Id and Example-REST-API-Key. I imagine you'd want those to match. Plus, you are setting them as the POST body of the request instead of as HTTP headers. You need to use one of the setHeader methods on httpPost instead. I would also recommend not explicitly setting Content-Type in such a manner. The content type is usually provided as part of the HttpEntity being posted.

To post the image content using HttpClient in Java, you would need to use a FileEntity that references the path of the file (/Users/thomas/Desktop/greep-small.png in your example). Right now you are posting the header values as name value pairs as I mentioned before.

Implementing curl -d would require doing something like passing a StringEntity to httpPost.setEntity() using the value you want to send.

Finally, the Java code is using some credentials that I don't see going on at all in the curl command.

Thanks for you detailed answer. I'll try your hints and let you know if it worked.

Thanks @laz, you made my day. I was using MultipartEntity, but to simulate --data-binary behavior, we really need to use FileEntity. Thanks a lot.

rest - how to translate curl -X post into java - Stack Overflow

java rest curl apache-httpclient-4.x
Rectangle 27 0

mapper.writeValueAsString(someObject)
(MediaType.APPLICATION_JSON)
{"attribute":"value","attribute":"value"}
param("filterId", filterId)
filterId
/press/group?filterId:filterIdString
curl -X POST -d '{"attribute":"value","attribute":"value"}' -H "Content-Type: application/json" "admin:password@localhost:8080/press/group?filterId:filterId" -i
-d
-H
admin:passwor@
-i

java - MockMvc show corresponding curl command or http request - Stack...

java api spring-mvc curl
Rectangle 27 0

'Curl' is just a library that is used to make HTTP requests in php. In android(java) you can achieve the same using the HttpURLConnection class. You can add your authentication string as a request property. Following example may help:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String oAuth = "Basic " + new String(new Base64().encode("oath authentication string"));
myURLConnection.setRequestProperty ("Authorization", oAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
//open the connection and write to the output stream & then read from input stream.

How to use the curl in android Twitter integration - Stack Overflow

android twitter twitter-oauth
Rectangle 27 0

Since you PUT data when you use curl this way, all you need to do is to implement a PUT request handler. In theory at least :)

@PUT
@Path("/user/folder")      
@Consumes("application/json")
public void receiveData(String data) { 
    ......
}

edit: didn't see the -X PUT at first. you want a PUT handler not a POST handler.

hi deadsven, i aldy have PUT method . so I just need to write variable "String data" in put method?Coz i am new to web service.thanks

yes sudo, the request body should be sent in into the data variable then.

btw for upload i used curl -T /home/student/a.jpg --data { Name: name....} localhost:8080/user/a.jpg . For that case I aldy have "String content" variable for upload ,so i need another variable to capture --data. But can I examine which one belong to which? thanks

web services - get data in java when http request sent by curl command...

java web-services data curl httprequest
Rectangle 27 0

a servlet takes care of the other end: it's basically a handler for http requests that lives inside a servlet container. If I understand you correctly, you're wanting to send an http request. You can do that using command-line tools like curl, or if you want to stay within java land, you could try this example on exampledepot. Use your favourite search engine to search for more examples, e.g. with search terms such as "sending GET requests through a url".

In your situation, where you need to send information for username and password, you would need to look at the html and find the url for the form element's action attribute. Then you need to find the names of the username and password fields. Using these names as url parameters, you can construct a GET request that mimics sending a form.

NOTE: usually storing a password in plain text in code and/or sending it in plain text to a website is not a good thing to do.

java - How to programmatically send a HTTP request with parameters? - ...

java http servlets
Rectangle 27 0

Runtime.getRuntime().exec("curl --data \"name=hell&&email=check@gmail.com&&phone=9845123134\" http://www.example.com");

http - Incoding curl request into Java String - Stack Overflow

java http curl
Rectangle 27 0

Heads up, the problem was authorization (in case anyone has this problem as well). Totally derped and forgot to send username/password.

HTTP POST request to JIRA using Java yields 400 bad request error, cur...

java http post jira jira-rest-api
Rectangle 27 0

There are numerous ways to achieve this. Below one is simplest in my openion, Agree it isnt very flexible but works.

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.codec.binary.Base64;

public class HttpClient {

    public static void main(String args[]) throws IOException {
        String stringUrl = "https://qualysapi.qualys.eu/api/2.0/fo/report/?action=list";
        URL url = new URL(stringUrl);
        URLConnection uc = url.openConnection();

        uc.setRequestProperty("X-Requested-With", "Curl");

        String userpass = "username" + ":" + "password";
        String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        uc.setRequestProperty("Authorization", basicAuth);

        InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
        // read this input

    }
}

Converting CURL request to HTTP Request Java - Stack Overflow

java curl