dphil
dphil

Reputation: 132

RESTful service call

I am using a chrome plugin and can successfully get my service to work:

enter image description here

I am now trying to get this same thing into my Java call. I'm having issues getting the Raw part into my Java service though. Any ideas?

  httpPost = new HttpPost(URL);
  nvps = new ArrayList<NameValuePair>();
  nvps.add(new BasicNameValuePair("Authorization", "Bearer " + token));
  nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

  //I know this part is incorrect, but I don't know what to do with it
  nvps.add(new BasicNameValuePair("{\"pCode\": \"\", \"rType\": \"Sales Case\", \"subject\": \"test3\", \"description\": \"test4\", \"lookupInfo\": \"test5\", \"aaNum\": \"\"}", ""));

  try
  {
    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
  } catch (UnsupportedEncodingException e)
  {
    e.printStackTrace();
  }

  HttpResponse response;
  try {
    response = client.execute(httpPost);
    BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    String builder = "";

    String line = in.readLine();
    System.out.println("line = " + line);
  } catch (ClientProtocolException e)
  {
    e.printStackTrace();
  } catch (IOException e)
  {
    e.printStackTrace();
  }
}

Upvotes: 1

Views: 171

Answers (3)

Justin Kyle Parton
Justin Kyle Parton

Reputation: 120

HttpClient

I have no idea what you are using to do your http calls, but for simplicity and sanity, use the httpclient from apache.

Example

    HttpPost post = new HttpPost(URL);

    post.setHeader("Content-type", "application/json");
    post.setHeader("Authorization", "Bearer " + token));
    post.setHeader("Cache-Control", "no-cache"));

    FileBody fileBody = new FileBody(file);
    StringBody pCode = new StringBody("SOME TYPE OF VALUE", ContentType.MULTIPART_FORM_DATA);
    StringBody rType = new StringBody("SOME TYPE OF VALUE", ContentType.MULTIPART_FORM_DATA);
    //
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("pCode", pCode);
    builder.addPart("rType", rType);
    HttpEntity entity = builder.build();
    try
    {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    }catch (UnsupportedEncodingException e)
    {
       e.printStackTrace();
    }

    HttpResponse response;
    try {
       response = client.execute(httpPost);
       BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
       String builder = "";

       String line = in.readLine();
       System.out.println("line = " + line);
    } catch (ClientProtocolException e)
    {
      e.printStackTrace();
    } catch (IOException e)
    {
    e.printStackTrace();
  }

}

This code has not been tested.

UPDATE

JSON IS just a fancy string (in java's perspective) so just add the following:

builder.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));

UPDATE 2

The above adds the JSON as a POST variable, not as the body.. Look AT This Post

Upvotes: 1

Ritesh Gune
Ritesh Gune

Reputation: 16729

You must keep header information and data at the appropriate place. Don't mix them up as you are doing now.

Understand the structure of Http requests:

  1. A Start-line where start-line = Request-Line | Status-Line

    eg. GET /hello.htm HTTP/1.1 (This is Request-Line sent by the client) HTTP/1.1 200 OK (This is Status-Line sent by the server)

  2. Zero or more header fields followed by CRLF (header information goes here) where message-header = field-name ":" [ field-value ]

    eg.

       User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3  
       Host: www.example.com
       Accept-Language: en, mi    
       Date: Mon, 27 Jul 2009 12:28:53 GMT
       Server: Apache
       Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
       ETag: "34aa387-d-1568eb00"
       Accept-Ranges: bytes
       Content-Length: 51
       Vary: Accept-Encoding
       Content-Type: text/plain
    
  3. An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields

  4. Optionally a message-body (content information goes here)

You can try following:

public void postData() {

    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    // pass the url as parameter and create HttpPost object.
    HttpPost post = new HttpPost(url);

    // Add header information for your request - no need to create 
    // BasicNameValuePair() and Arraylist.
    post.setHeader("Authorization", "Bearer " + token);
    post.setHeader("Content-Type", "application/json");
    post.setHeader("Cache-Control", "no-cache");    

    try {
    // put your content as follows:
    List<NameValuePair> form_data = new ArrayList<NameValuePair>(); 
    form_data.add(new BasicNameValuePair("pCode", ""));
    form_data.add(new BasicNameValuePair("rType", "Sales Case"));
    form_data.add(new BasicNameValuePair("subject", "test3"));
    form_data.add(new BasicNameValuePair("description", "test4"));
    form_data.add(new BasicNameValuePair("lookupInfo", "test5"));
    form_data.add(new BasicNameValuePair("aaNum", ""));

    // pass the content as follows:
    post.setEntity(new UrlEncodedFormEntity(form_data,
                        HTTP.UTF_8));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(post);

    // TODO: Process your response as you would like.

    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

Upvotes: 0

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

You're mixing up headers and content:

These are headers:

nvps.add(new BasicNameValuePair("Authorization", "Bearer " + token));
nvps.add(new BasicNameValuePair("Content-Type", "application/json"));
nvps.add(new BasicNameValuePair("Cache-Control", "no-cache"));

And this is the content:

nvps.add(new BasicNameValuePair("{\"pCode\": \"\", \"rType\": \"Sales Case\", \"subject\": \"test3\", \"description\": \"test4\", \"lookupInfo\": \"test5\", \"aaNum\": \"\"}", ""));

Here you set the content:

httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

You don't need to do multipart, just set the String content without encoding it, and set the headers with httpPost.addHeader().

Upvotes: 1

Related Questions