2013-03-25 52 views
0

我有一个android需求从url解析json内容并完成它们,现在我需要将结果作为json内容发送回服务器url。搜索了很多以前的帖子,但大多数指定了如何下载和解析json内容。任何有关如何在json中将内容发布到url的输入/示例都将有巨大的帮助!写json内容到url android

编辑:下面是附加的示例代码我试图

try { 

     URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/json"); 

     String input = "{\"qty\":100,\"name\":\"iPad 4\"}"; 

     OutputStream os = conn.getOutputStream(); 
     os.write(input.getBytes()); 
     os.flush(); 

     if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { 
      throw new RuntimeException("Failed : HTTP error code : " 
        + conn.getResponseCode()); 
     } 

     BufferedReader br = new BufferedReader(new InputStreamReader(
       (conn.getInputStream()))); 

     String output; 
     System.out.println("Output from Server .... \n"); 
     while ((output = br.readLine()) != null) { 
      System.out.println(output); 
     } 

     conn.disconnect(); 

    } catch (MalformedURLException e) { 

     e.printStackTrace(); 

    } catch (IOException e) { 

     e.printStackTrace(); 

    } 

在执行此,让连接被拒绝,java.net.connect例外!请帮忙!!

+0

您应该考虑添加示例网址_应该看起来如何。 – 2013-03-25 04:17:22

+0

添加样本,请添加你的意见! – bharath 2013-03-25 16:50:50

+0

我希望你有一个真正的URL地址,你把本地主机?如果web服务在该地址正确响应,您是否尝试过? (例如使用cURL?像这样:'curl -d“param1 = value1&param2 = value2”http:// yourURLhere:8080 /?otherparam = othervalue') – Patrick 2013-03-25 16:58:19

回答

1

您可以使用下面的方法发送您的JSON请求。

public static HttpResponse sendRequest(String url, String request) throws Exception 
{ 
    //Create the httpclient to make request 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 

    //create an HttpPost request object 
    HttpPost httpost = new HttpPost(url); 

    //Create the String entity to be passed to the HttpPost request 
    StringEntity se = new StringEntity(request)); 

    //set the created StringEntity 
    httpost.setEntity(se); 

    //the intended 
    httpost.setHeader("Accept", "application/json"); 
    httpost.setHeader("Content-type", "application/json"); 

    return httpclient.execute(httpost); 
} 

希望这会有所帮助。

+0

字符串请求是您的json字符串吗? – Dyna 2014-01-10 19:26:33