从 Apache Http POST 请求返回字符串(Android)

Posted

技术标签:

【中文标题】从 Apache Http POST 请求返回字符串(Android)【英文标题】:Return String from Apache Http POST Request (Android) 【发布时间】:2019-03-30 14:37:36 【问题描述】:

我正在尝试从我的 andorid 应用程序中的 HTTP 发布请求中获取 json string。使用来自this post 的解决方案,此处也显示了代码。

public void post(String completeUrl, String body) 
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(completeUrl);
httpPost.setHeader("Content-type", "application/json");
try 
    StringEntity stringEntity = new StringEntity(body);
    httpPost.getRequestLine();
    httpPost.setEntity(stringEntity);

    httpClient.execute(httpPost);
 catch (Exception e) 
    throw new RuntimeException(e);


我从异步任务内部调用 post(用于在单独的线程上处理网络访问)。

String result;
result = post("https://StringURLGoesHere.com/", "jsonStringBodyGoesHere");

根据documentation for HttpClient class,要处理响应,我需要在 HttpClient.execute() 方法中添加第二个参数 ResponseHandler。

public interface ResponseHandler<T> 
T handleResponse(HttpResponse var1) throws ClientProtocolException, IOException;

我就是这样做的:

public String post(String completeUrl, String body) 
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(completeUrl);
        httpPost.setHeader("Content-type", "application/json");
        try 
            StringEntity stringEntity = new StringEntity(body);
            httpPost.getRequestLine();
            httpPost.setEntity(stringEntity);

            ResponseHandler<String> reply = new ResponseHandler<String>() 
                @Override
                public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException 
                    return httpResponse.toString();
                
            ;
            return httpClient.execute(httpPost,reply);


         catch (Exception e) 
            throw new RuntimeException(e);
        
    

我在我的应用程序的文本视图中显示字符串。上面写着:

org.apache.http.message.BasicHttpResponse@1446ef0c

org.apache.http.message.BasicHttpResponse@b83bd3d

org.apache.http.message.BasicHttpResponse@1c4c9e1d

等等。

为什么我得到这个返回作为一个字符串?为了让 json 对象的字符串在 post 后返回,应该改变什么?

【问题讨论】:

【参考方案1】:
Try like below to capture HttpRepose to see your response;
HttpClient request = HttpClientBuilder.create().build();        
HttpGet get = new HttpGet(url);
get.setHeader( "Authorization", token);
HttpResponse response = null;
try 
     response = request.execute( get );
 catch ( ClientProtocolException e ) 
     // TODO Auto-generated catch block
     e.printStackTrace();
 catch ( IOException e ) 
    // TODO Auto-generated catch block
     e.printStackTrace();


BufferedReader rd = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) );

StringBuffer result = new StringBuffer();
String line = "";
while ( (line = rd.readLine()) != null ) 
      result.append( line );


System.out.println( response.getStatusLine().getStatusCode() );
System.out.println( result.toString() );

【讨论】:

这个答案很详细,为什么在这种情况下建议使用缓冲阅读器?【参考方案2】:

你可以这样做:

    httpPost.setEntity(entity);
    HttpResponse response = httpclient.execute(httpPost);
    String responseString = new BasicResponseHandler().handleResponse(response);
    return responseString;  //this is your want

【讨论】:

我收到 java.io.IOException: Attempted read on closed stream。什么可能导致这种情况?

以上是关于从 Apache Http POST 请求返回字符串(Android)的主要内容,如果未能解决你的问题,请参考以下文章

HTTP post/API 请求在 bash 上从 CURL 发送时有效,从 Apache http 失败

使用 $http.post (angular) 和 bodyparser.text() 发送字符串请求时,请求正文作为对象返回?

使用 Apache Http Client 4.5.3 从 jdk1.6.0_45 到 API Gateway 的简单 POST 请求

Typescript HttpClient.post 从 json 格式的字符串返回错误请求

asp.net 发送http get请求,然后取返回来的文件或者字符串

POST和GET区别