3

サーバーは と の 2 つのパラメータを取りStringますJSON。プロンプト、正しく転送JSONし、POST リクエストで文字列を送信しますか?

try {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("my_url");
    List parameters = new ArrayList(2);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("par_1", "1");
    jsonObject.put("par_2", "2");
    jsonObject.put("par_3", "3");
    parameters.add(new BasicNameValuePair("action", "par_action"));
    parameters.add(new BasicNameValuePair("data", jsonObject.toString()));
    httpPost.setEntity(new UrlEncodedFormEntity(parameters));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    Log.v("Server Application", EntityUtils.toString(httpResponse.getEntity())+" "+jsonObject.toString());

} catch (UnsupportedEncodingException e) {
    Log.e("Server Application", "Error: " + e);
} catch (ClientProtocolException e) {
    Log.e("Server Application", "Error: " + e);
} catch (IOException e) {
    Log.e("Server Application", "Error: " + e);
} catch (JSONException e) {
    e.printStackTrace();
}
4

2 に答える 2

2

コードのスケーラビリティを高めるためにRestClientクラスを使用する方がはるかに優れていると思いますが、基本的には、基本的なソリューションにはあなたのコードが適していると思います.ここでは、POSTまたはGETを実装する適切なRestClientクラスを投稿します。

public class RestClient {

private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String url;
private String response;
private int responseCode;

public String GetResponse()
{
    return response;
}

public int GetResponseCode()
{
    return responseCode;
}

public RestClient(String url)
{
    this.url = url;
    params = new ArrayList<NameValuePair>();
    headers = new ArrayList<NameValuePair>();
}

public void AddParam(String name, String value)
{
    params.add(new BasicNameValuePair(name, value));
}

public void AddHeader(String name, String value)
{
    headers.add(new BasicNameValuePair(name, value));
}

public void Execute(RequestType requestType) throws Exception
{
    switch(requestType)
    {
        case GET:
        {
            String combinedParams = "";
            if (!params.isEmpty())
            {
                combinedParams += "?";
                for (NameValuePair p : params)
                {
                    String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");

                    if  (combinedParams.length() > 1)
                        combinedParams += "&" + paramString;
                    else
                        combinedParams += paramString;
                }
            }
            HttpGet request = new HttpGet(url + combinedParams);

            for (NameValuePair h: headers)
                request.addHeader(h.getName(),h.getValue());

            ExecuteRequest(request, url);
            break;
        }
        case POST:
        {
            HttpPost request = new HttpPost(url);

            for (NameValuePair h : headers)
            {
                request.addHeader(h.getName(), h.getValue());
            }

            if(!params.isEmpty()){
                request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            }

            ExecuteRequest(request, url);
            break;
        }
    }
}

public void ExecuteRequest(HttpUriRequest request, String url) 
{
    HttpClient client = new DefaultHttpClient();
    HttpResponse httpResponse;
    try
    {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null)
        {
            InputStream in = entity.getContent();
            response = ConvertStreamToString(in);
            in.close();
        }
    }
    catch (ClientProtocolException e)  {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
        } catch (IOException e) {
        Log.e("REST_CLIENT", "Execute Request: " + e.getMessage()); 
        client.getConnectionManager().shutdown();

        e.printStackTrace();
    }       
}

private String ConvertStreamToString(InputStream in)
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try 
    {
        while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    }
    catch (IOException e) 
    {
        e.printStackTrace();
    } 
    finally 
    {
        try 
        {
            in.close();
        } 
        catch (IOException e) 
        {
             Log.e("REST_CLIENT", "ConvertStreamToString: " + e.getMessage());  
            e.printStackTrace();
        }
    }
    return sb.toString();
}

これにより、次のような POST を簡単に実行できます。

RestClient rest = new RestClient(url)
rest.addHeader(h.name,h.value);
rest.Execute(RequestType.POST);
于 2013-04-19T20:26:21.253 に答える