gpt4 book ai didi

java - Android Http 请求 POST JSON

转载 作者:行者123 更新时间:2023-12-02 00:42:04 25 4
gpt4 key购买 nike

我正在尝试创建一个函数来发出请求,但它给出了一些错误,我已经向互联网授予了权限,但仍然

这是我的代码:

public String request(String Url,JSONObject Data){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Url);
InputStream inputstream;
String content = "";


try {

httppost.setEntity(new StringEntity(Data.toString()));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
while(true){
if(entity != null){
inputstream = entity.getContent();
content = inputstream.toString();
break;
}
}

} catch (Exception ex) {
return ex.toString();
}

return content;
}

输入:

JSONObject data = new JSONObject();
data.put("teste","teste");
String response = request('urlExample',data);
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();

输出:

android.os.NetworkOnMainThreadExecption

最佳答案

我建议您使用 AsyncTask,正如我在评论中提到的:

private class LongOperation extends AsyncTask<Void, Void, String> {

private String mUrl;
private JSONObject mData;

public LongOperation(String url, JSONObject data) {
mUrl = url;
mData = data;
}

@Override
protected String doInBackground(Void... params) {
return request(mUrl, mData);
}

@Override
protected void onPostExecute(String response) {
Toast.makeText(getApplicationContext(),response,
Toast.LENGTH_SHORT).show();
}

@Override
protected void onPreExecute() {}

@Override
protected void onProgressUpdate(Void... values) {}
}

您可以按如下方式启动 AsyncTask:

JSONObject data = new JSONObject();
data.put("teste","teste");
new LongOperation('urlExample', data).execute();

关于java - Android Http 请求 POST JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57930178/

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