2013-03-25 46 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