gpt4 book ai didi

java - Android 从 URL 检索 JSON 对象

转载 作者:行者123 更新时间:2023-11-29 20:25:34 25 4
gpt4 key购买 nike

我正在开发一个应用程序,该应用程序对一个回显 JSON 对象的 php 脚本进行 API 调用。通过浏览器手动测试 php 文件会返回预期的信息,但我的应用程序的行为就好像返回的字符串是空的(在我到达解码 JSON 对象之前)。

这是我的代码 fragment 。我已经在我的应用程序中多次成功地使用这个脚本来获取回显字符串的 api。

String urlParameters = 
"request=item_search&item_num=" + barcode + "&ou=" + OU + "&user_tag=" + initials + "&version=" + version + "&scan_point=return";
URL url = null;
try {
if (testMode == true)
{
url = new URL("http://URL/api.php");
}
else
{
url = new URL("http://URL/api.php");
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
StringBuilder output = new StringBuilder();
try
{
assert url != null;
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
writer.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null)
{
output.append(line);
}
writer.close();
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String outputString = output.toString();

最佳答案

你试过了吗OkHttp.

HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

你可以试试following code :

package com.squareup.okhttp.guide;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;

public class GetExample {
OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();

Response response = client.newCall(request).execute();
return response.body().string();
}

public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}

更多内容可以访问:

Vogella's article

OkHttp 2.0

关于java - Android 从 URL 检索 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32608916/

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