我是Android的新手,正在尝试通过httpURLConnection将String json传递给API,但始终会返回错误。这是我在网上找到的应该工作的代码的副本。我试图创建另一个扩展AsyncTask的类,但是我不知道如何从API返回结果。有人可以告诉我我做错了什么,并帮助我纠正它。
String json = "{\"requests\":[{\"image\":{\"content\":\"" + encodedString + "\"},\"features\":[{\"type\":\"LABEL_DETECTION\",\"maxResults\":\"10\"}]}]}";
try{
URL urlObj = new URL(urlVisit);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("test", "result from server: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
控制台给出的错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: edmt.dev.androidcamera2api, PID: 22584
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1460)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(Unknown Source:0)
at edmt.dev.androidcamera2api.MainActivity$2.onClick(MainActivity.java:177)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
答案 0 :(得分:0)
从堆栈跟踪中,您正尝试从MainThread执行网络调用。
E/AndroidRuntime: FATAL EXCEPTION: main
Process: edmt.dev.androidcamera2api, PID: 22584
android.os.NetworkOnMainThreadException
您应该将网络调用包装在AsyncTask或任何其他不会阻塞UI的后台线程中。
下面是一个代码片段,可以帮助您入门:
class TestAsync extends AsyncTask<String, Integer, String>
{
protected void onPreExecute (){
super.onPreExecute();
}
protected String doInBackground(String... params) {
// wrap the network call here
String json = "{\"requests\":[{\"image\":{\"content\":\"" + encodedString + "\"},\"features\":[{\"type\":\"LABEL_DETECTION\",\"maxResults\":\"10\"}]}]}";
StringBuilder result = new StringBuilder();
try{
URL urlObj = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
protected void onProgressUpdate(Integer...a){
super.onProgressUpdate(a);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("test", "result from server: " + result);
}
}
要调用AsyncTask,
new TestAsync().execute(urlVisit);
答案 1 :(得分:0)
您是否在AndroidManifest.xml
上添加了Internet权限?
<uses-permission android:name="android.permission.INTERNET"/>