如何将JSON格式的数据从java中的RESTful客户端传递给服务器。这适用于Activity中的POST方法

时间:2014-05-19 05:46:59

标签: java json rest eclipselink

我正在创建一个Web应用程序。我想使用Java SE应用程序执行管理操作。为此,我在SE项目中创建了一个RESTful Client。我需要从客户端将JSON数据格式传递给服务器。我试过这个:

public static String post(String urlStr, String paramName[],String paramVal[]) throws Exception {         
  URL url = new URL(urlStr);

  String login = "kermit";

  String password = "kermit";

  String loginPassword = login+ ":" + password;

  String encoded = new Sun.misc.BASE64Encoder().encode(loginPassword.getBytes());

  HttpURLConnection conn =(HttpURLConnection) url.openConnection();

  conn.setRequestMethod("POST");
  conn.setDoOutput(true);
  conn.setDoInput(true);
  conn.setUseCaches(false);
  conn.setAllowUserInteraction(false);
  conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded")
  OutputStream out = conn.getOutputStream();

  Writer writer = new OutputStreamWriter(out, "UTF-8");

  for (int i = 0; i < paramName.length; i++) {
      writer.write(paramName[i]);
      writer.write("=");
      writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
      writer.write("&");
  }
  writer.close();
  out.close();

  if (conn.getResponseCode() != 200)  {
      throw new IOException(conn.getResponseMessage());
  }


  BufferedReader rd = new BufferedReader(
  new InputStreamReader(conn.getInputStream()));
  StringBuilder sb = new StringBuilder();
  String line;

  while ((line = rd.readLine()) != null)  {
      sb.append(line);
  }
  rd.close();

  conn.disconnect();
  return sb.toString();
}

并尝试了这个

public static String post(String urlStr)throws IOException 
{   
    DefaultHttpClient dhc = new DefaultHttpClient();
    dhc.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials("kermit", "kermit"));
    HttpPost hp = new HttpPost("http://localhost:8080/activiti-rest/service/process-instance");
    hp.setEntity(new StringEntity("{\"processDefinitionId\":\"helloworld:1\"}", "UTF-8"));
    HttpResponse processResponse = dhc.execute(hp);
    System.out.println(IOUtils.toString(processResponse.getEntity().getContent()));
    dhc.getConnectionManager().shutdown();

              System.out.println( "this is post " );
              StringBuilder sb = new StringBuilder();
              return sb.toString(); 
}

但我得到以下例外

Exception in thread "main" java.io.IOException: Method Not Allowed
at SingleFileClient.post(SingleFileClient.java:135)
at SingleFileClient.main(SingleFileClient.java:58)

这是另一个网址:

Exception in thread "main" java.lang.IllegalStateException: Target host must not be  null, or set in parameters.
at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:615)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:319)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at json.post(json.java:121)
at json.main(json.java:58)

有时404,405,错误发生。有什么解决方案吗?要么 如何从JAVA SE中的RESt API向服务器发送JSON格式数据?

1 个答案:

答案 0 :(得分:0)

如果您将数据发布到服务器,那么json格式将在正文中提供 为了阅读正文,请尝试在ServletRequest中使用getInputStream()

阅读后,您可以使用GSON

将此InputStream转换为对象表示