0

URLからjsonコンテンツを解析するAndroid要件があり、それらを完了しました。結果をjsonコンテンツとしてサーバーURLに送り返す必要があります。以前の多くの投稿を検索しましたが、ほとんどが json コンテンツをダウンロードして解析する方法を指定しています。json で URL にコンテンツを投稿するための開始方法の入力/例は、非常に役立ちます!

編集:以下は、私が試しているもののサンプルコードです

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 例外が発生しました。助けてください!!

4

1 に答える 1

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

お役に立てれば。

于 2013-03-25T17:05:00.967 に答える