gpt4 book ai didi

java - 读取 HttpPost 响应

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:45 27 4
gpt4 key购买 nike

我正在使用此代码向 http 服务器发送请求:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost( "http://192.168.0.1/test.php" );
HttpResponse response = null;
try {
List< NameValuePair > nameValuePairs = new ArrayList< NameValuePair >( 1 );
nameValuePairs.add( new BasicNameValuePair( "num", "2" ) );
post.setEntity( new UrlEncodedFormEntity( nameValuePairs ) );
response = client.execute( post );
}
catch( ClientProtocolException e ) {
...
}
catch( IOException e ) {
...
}

响应只不过是一个简单的 String。如何将此响应作为 String 读取? HttpResponse 似乎没有直接执行此操作的方法。

最佳答案

我已经创建了这个辅助方法,用于在 Android 中通过 POST 方法发送数据和特殊 header (如果您没有任何自定义 header ,则 header HashMap 可能为空):

public static String getStringContent(String uri, String postData, 
HashMap<String, String> headers) throws Exception {

HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(uri));
request.setEntity(new StringEntity(postData));
for(Entry<String, String> s : headers.entrySet())
{
request.setHeader(s.getKey(), s.getValue());
}
HttpResponse response = client.execute(request);

InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
{
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);

}
buf.close();
ips.close();
return sb.toString();

}

关于java - 读取 HttpPost 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4361601/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com