1

I have a CURL as follows. When I call this from the command prompt, after process it returns JSON value. If I access this CURL from PHP also it gives the proper result. Now I want to access this in Java to integrate it to a java project.

curl xx.xx.xx.xx:5000/models/images/one.json -XPOST -F job_id=20yy0811-wq50r5-b629 -F image_url=http://www.mysite/public/testimage.jpg

I tried to implement it some examples I got from internet, shows HTTP errors like 400, 405 etc.

String stringUrl = "http://xx.xx.xx.xx:5000/models/images/one.json";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();

uc.setRequestProperty("X-Requested-With", "Curl");
uc.setRequestProperty("format","json");
uc.setRequestProperty("job_id", "20yy0811-wq50r5-b629");
uc.setRequestProperty("image_url", "http://www.mysite/public/testimage.jpg");
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream()); 

It gives the result:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 405 for URL:

Tried another code:

String url = "http://xx.xx.xx.xx:5000/models/images/one.json";

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.setRequestProperty("job_id", "20yy0811-wq50r5-b629");
conn.setRequestProperty("image_url", "http://www.mysite/public/testimage.jpg");

String data =  "{\"format\":\"json\"}";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
new InputStreamReader(conn.getInputStream()); 

It gives the result:

java.io.IOException: Server returned HTTP response code: 400 for URL:

My requirement is:

URL: xx.xx.xx.xx:5000/models/images/one.json

Parameters: job_id, image_url

Return value : json

How can I convert this CURL to java code? If someone can change this CURL to Java code it would be great.

SOLUTION:

  • Download Apache HttpComponents
  • Follow the steps in http://www.journaldev.com/7146/apache-httpclient-example-to-send-get-post-http-requests

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://xx.xx.xx.xx:5000/models/images/one.json");
    //httpPost.addHeader("User-Agent", USER_AGENT);
    
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("job_id", "20yy0811-wq50r5-b629"));
    urlParameters.add(new BasicNameValuePair("image_url", "http://www.mysite/public/testimage.jpg"));
    
    
    HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
    httpPost.setEntity(postParams);
    
    CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
    
    System.out.println("POST Response Status:: "
            + httpResponse.getStatusLine().getStatusCode());
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            httpResponse.getEntity().getContent()));
    
    String inputLine;
    StringBuffer response = new StringBuffer();
    
    while ((inputLine = reader.readLine()) != null) {
        response.append(inputLine);
    }
    reader.close();
    
    // print result
    System.out.println(response.toString());
    httpClient.close();
    
San
  • 666
  • 7
  • 27
  • parameters are url form encoded parameters or header values? – Abdullah Shoaib Aug 12 '15 at 11:47
  • Yes, one parameter is an image url. – San Aug 12 '15 at 11:49
  • The `-F` for cURL is for multipart data. Add the `-v` switch to the request to see all the headers. You will see. If you don't know how to properly format multipart data, then I suggest looking into a library that already implements such feature. – Paul Samsotha Aug 12 '15 at 12:02
  • Jusing Apache HttpClient is way easier that HttpUrlConnection. – Michael-O Aug 12 '15 at 12:23
  • @peeskillet, How do I pass -v and -F? – San Aug 12 '15 at 12:37
  • On the command line with your curl request. I am not saying that is a solution. I am just saying to get verbose output on the curl request, use the `-v` switch. This will only give you more information about your curl request. I said to do that just so you can see that the request is a multipart request, based on your use of `-F` switches for your data. Like I said, if you know nothing about multipart and it's format, you should look into a library that can send multipart. Formatting the output is not easy for someone who has no understanding of the output – Paul Samsotha Aug 12 '15 at 12:47
  • @Michael-O, do you have a sample code? – San Aug 13 '15 at 10:28
  • @san http://hc.apache.org/httpcomponents-client-ga/quickstart.html – Michael-O Aug 13 '15 at 18:33

1 Answers1

1

setRequestProperty() sets the headers.To set Form parameters, try this:

String url = "http://xx.xx.xx.xx:5000/models/images/one.json";

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);

conn.setRequestMethod("POST");

//build it this way
Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("firstParam", paramValue1)
        .appendQueryParameter("secondParam", paramValue2)
        .appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();

You need to import ApacheHttpClient lib to use Uri.Builder class.

source: https://stackoverflow.com/a/29053050/856007

Community
  • 1
  • 1
Abdullah Shoaib
  • 2,065
  • 2
  • 18
  • 26
  • I'm using Java 1.8. for Uri.Builder class which jar I need to import?. it seems Uri.Builder is for Android. – San Aug 13 '15 at 09:22
  • you need to import ApacheHttpClient – Abdullah Shoaib Aug 13 '15 at 13:08
  • Yes! Thank you very much it's working now! I have followed the code in http://www.journaldev.com/7146/apache-httpclient-example-to-send-get-post-http-requests – San Aug 13 '15 at 13:12