RESTful服务电话

时间:2014-07-29 20:25:44

标签: java rest

我正在使用Chrome插件,可以成功使我的服务工作:

enter image description here

我现在正试图在Java调用中使用同样的东西。我遇到了将Raw部分放入Java服务的问题。有什么想法吗?

  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();
  }
}

3 个答案:

答案 0 :(得分:1)

的HttpClient

我不知道您使用什么来进行http调用,但为了简单和理智,请使用apache中的httpclient。

实施例

    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();
  }

}

此代码尚未经过测试。

更新

JSON只是一个奇特的字符串(在java的角度来看)所以只需添加以下内容:

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

更新2

上面将JSON添加为POST变量,而不是正文.. Look AT This Post

答案 1 :(得分:1)

您正在混合标题和内容:

这些是标题:

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

这就是内容:

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

在此设置内容:

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

您不需要执行多部分,只需设置字符串内容而不用对其进行编码,并使用httpPost.addHeader()设置标题。

答案 2 :(得分:0)

您必须将标题信息和数据保存在适当的位置。不要像现在这样混淆它们。

了解Http请求的结构:

  1. 一个起始线 start-line = Request-Line | Status-Line

    例如。 GET /hello.htm HTTP/1.1(这是客户发送的请求行)     HTTP/1.1 200 OK(这是服务器发送的状态行)

  2. 零个或多个标题字段后跟CRLF(标题信息在此处) 其中message-header = field-name ":" [ field-value ]

    例如。

       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. 表示标题字段结尾的空行(即CRLF前面没有任何内容的行)

  4. 可选择邮件正文(内容信息在此处)

  5. 您可以尝试以下操作:

    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
        }
    }