【问题标题】:How do I display a Java HttpPost object as a string?如何将 Java HttpPost 对象显示为字符串?
【发布时间】:2012-09-06 16:29:55
【问题描述】:

我正在 Android 中创建一个 HttpPost 对象以与客户端操作的服务器进行通信。不幸的是,服务器没有为我们提供非常有用的错误消息;我想将 HttpPost 对象的内容作为字符串查看,以便我可以将其发送给我们的客户,他可以将其与他的期望进行比较。

如何将 HttpPost 对象转换为反映它到达服务器时的外观的字符串?

【问题讨论】:

  • 您的服务器代码使用哪种语言?是 Servlet(或)PHP(或)别的吗?
  • .NET,但我无法控制服务器。

标签: java android http-post


【解决方案1】:

应该在执行后使用

public static String httpPostToString(HttpPost httppost) {
    StringBuilder sb = new StringBuilder();
    sb.append("\nRequestLine:");
    sb.append(httppost.getRequestLine().toString());

    int i = 0;
    for(Header header : httppost.getAllHeaders()){
      if(i == 0){
          sb.append("\nHeader:");
      }
        i++;
        for(HeaderElement element : header.getElements()){
            for(NameValuePair nvp :element.getParameters()){
                sb.append(nvp.getName());
                sb.append("=");
                sb.append(nvp.getValue());
                sb.append(";");
            }
        }
    }
    HttpEntity entity = httppost.getEntity();

    String content = "";
    if(entity != null){
        try {

            content = IOUtils.toString(entity.getContent());
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    sb.append("\nContent:");
    sb.append(content);


    return sb.toString();
}

snippet

【讨论】:

【解决方案2】:

我通常以这种方式发帖(服务器答案是一个 JSON 对象):

    try {
        postJSON.put("param1", param1);
        postJSON.put("param2",param2);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    String result = JSONGetHTTP.postData(url);
    if (result != null) {
        try {

            JSONObject jObjec = new JSONObject(result);

            }
        } catch (JSONException e) {
            Log.e(TAG, "Error setting data " + e.toString());
        }
    }

而 postData 是:

public static String postData(String url, JSONObject obj) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = null;
    try {
        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 30000);
        HttpConnectionParams.setSoTimeout(myParams, 30000);
        httpclient = new DefaultHttpClient(myParams);

    } catch (Exception e) {
        Log.e("POST_DATA", "error in httpConnection");
        e.printStackTrace();
    }

    InputStream is = null;
    try {
        HttpPost httppost = new HttpPost(url.toString());
        //Header here   httppost.setHeader();
        StringEntity se = new StringEntity(obj.toString());

        httppost.setEntity(se);

        HttpResponse response = httpclient.execute(httppost);

        HttpEntity entity = response.getEntity();
        // // Do something with response...
        is = entity.getContent();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // convert response to string
    BufferedReader reader = null;
    String result = null;
    try {
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    } finally {

        try {
            if (reader != null)
                reader.close();
            if (is != null)
                is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    if (result != null) {
        try {
            @SuppressWarnings("unused")
            JSONObject jObjec = new JSONObject(result);

        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
    }

    return result;
}

希望对你有帮助

【讨论】:

    【解决方案3】:

    好吧,我实际上使用NameValuePair 完成了HTTP-Post......我正在展示我用来执行HTTP-Post 然后将响应转换为@987654324 的代码 @

    参见下面的方法代码:

    public String postData(String url, String xmlQuery) {
    
    
    
    final String urlStr = url;
    final String xmlStr = xmlQuery;
    final StringBuilder sb  = new StringBuilder();
    
    
    Thread t1 = new Thread(new Runnable() {
    
    public void run() {
    
        HttpClient httpclient = new DefaultHttpClient();
    
        HttpPost httppost = new HttpPost(urlStr);
    
    
        try {
    
             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    
             nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
    
             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
             HttpResponse response = httpclient.execute(httppost);
    
             Log.d("Vivek", response.toString());
    
            HttpEntity entity = response.getEntity();
            InputStream i = entity.getContent();
    
            Log.d("Vivek", i.toString());
            InputStreamReader isr = new InputStreamReader(i);
    
            BufferedReader br = new BufferedReader(isr);
    
            String s = null;
    
    
            while ((s = br.readLine()) != null) {
    
                Log.d("YumZing", s);
                sb.append(s);
            }
    
    
            Log.d("Check Now",sb+"");
    
    
    
    
            } catch (ClientProtocolException e) {
    
                    e.printStackTrace();
    
                    } catch (IOException e) {
    
                        e.printStackTrace();
                    } 
                }
    
            });
    
            t1.start();
            try {
                t1.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
    
            System.out.println("Getting from Post Data Method "+sb.toString());
    
            return sb.toString();
        }
    

    【讨论】:

    • 转换响应没有任何问题;这是我感兴趣的电话,但还是谢谢你。
    • @AndrewWyld 不介意,但我认为你错过了我说我正在做HTTP Post using NamePairValue的部分
    猜你喜欢
    • 2014-08-02
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2023-03-28
    • 2015-05-24
    • 2020-04-19
    • 2012-01-22
    • 2016-05-15
    相关资源
    最近更新 更多