2

私はAndroid用のアプリケーションを作成しています.Javaを使用してwww.example.comアドレスにリクエストする必要があります. 問題は、POST パラメーターを送信する必要があり、いくつかの情報を検索していて、クロスドメインなどについて何かを見つけたことです。誰かがリクエストに到達して回答を得るのを手伝ってもらえますか?

次のコードを実行しようとしましたが、機能しませんでした:

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://www.example.com");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("param1", "val"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

解決:::::::::::::

  try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://www.example.com");

                ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

                postParameters.add(new BasicNameValuePair("key", "val"));
                postParameters.add(new BasicNameValuePair("key2", "val2"));


                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                        postParameters);
                post.setEntity(formEntity);

                    HttpResponse response = client.execute(post);
                        //inputStreamToString method
                    String data = inputStreamToString(response.getEntity()
                            .getContent());
                    return data;
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

inputStreamToString メソッド

private String inputStreamToString(InputStream is) {
        String s = "";
        String line = "";

        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                s += line;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Return full string
        return s;
    }
4

1 に答える 1