gpt4 book ai didi

android - 在 Android 中发布 JSON 和检索响应

转载 作者:搜寻专家 更新时间:2023-11-01 08:07:30 26 4
gpt4 key购买 nike

我正在尝试将 JSON 消息发布到站点并检索返回的 JSON 消息。
java.net.ProtocolException:方法不支持请求正文:POST有谁知道出了什么问题?提前致谢

                 HttpURLConnection conn=null;
try{
URL url=new URL(urlString);
String userPassword = userName +":" + passWord;
byte[] bytes=Base64.encode(userPassword.getBytes(),Base64.DEFAULT);
String stringEncoding = new String(bytes, "UTF-8");

conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "Basic " + stringEncoding);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
Log.i("Net", "length="+conn.getContentLength());
Log.i("Net", "contentType="+conn.getContentType());
Log.i("Net", "content="+conn.getContent());
conn.connect();

}catch(Exception e){
Log.d("Url Formation Connection", e.toString());
}

//输出{ 尝试{

            String requestString="{“ ";


wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(requestString.toString());
wr.flush();

//input{
BufferedReader rd = null;
String response=" ";


is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer responseBuff = new StringBuffer();
while ((line = rd.readLine()) != null) {
// Process line...
responseBuff.append(line);
}
response = responseBuff.toString();
Log.d("response", response);
}catch(Exception e){
Log.d("buffer error", e.toString());
}finally {
if (is != null) {
try {
wr.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

最佳答案

可能是您连接的服务器不允许 POST 操作。我会先尝试 GET 请求,看看您是否拥有该 Web 服务方法的权限。

此外,您可以使用更简单的 HttpClient 试试运气,尽管我自己还没有测试过此解决方案:http://www.geekmind.net/2009/11/android-simple-httpclient-to.html

关于android - 在 Android 中发布 JSON 和检索响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13128516/

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