尝试将图像从我的应用程序发送到服务器时出现问题。我知道崩溃的地方。 这些是我的文件:
RestClient.java
package edu.gvsu.cis.masl.camerademo;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class RestClient {
private static final int DEFAULT_CONNECTION_TIMEOUT = 30000;
private static final int DEFAULT_RECEIVE_TIMEOUT = 60000;
//private static final String AUTHORIZATION = "Authorization";
private static final String CONTENT_TYPE = "Content-Type";
private static final String JSON_CONTENT_TYPE = "application/json; charset=utf-8";
private static final String UTF8 = "UTF8";
private static final String DEBUG = RestClient.class.getName();
public Result put(String url, String json) {
return executeRequest(new HttpPut(url), json, DEFAULT_RECEIVE_TIMEOUT);
}
private Result executeRequest(HttpEntityEnclosingRequestBase request, String json, int timeout) {
request.addHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
try {
request.setEntity(new StringEntity(json,UTF8));
}catch(UnsupportedEncodingException e) {
Log.e(DEBUG, e.getMessage());
return Result.error();
}
return executeRequest(request,timeout);
}
private Result executeRequest(HttpUriRequest request, int timeout) {
int responseCode = -1;
String responseContent = null;
//request.addHeader(AUTHORIZATION, encodeCredentials(userCredentials));
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, timeout);
HttpClient client = new DefaultHttpClient(httpParams);
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
responseCode = response.getStatusLine().getStatusCode();
if(entity!=null) {
responseContent = EntityUtils.toString(entity, UTF8);
}
}catch(IOException e) {
Log.e(DEBUG, e.getMessage());
return Result.error();
}
return new Result(responseCode, responseContent);
}
}
ImageDTO.java:
public class ImageDTO {
public String id;
public String image;
public ImageDTO(String id, String image) {
this.id = id;
this.image=image;
}
}
Result.java:
package edu.gvsu.cis.masl.camerademo;
public class Result {
public static final int COMMUNICATION_ERROR = -1;
public static final int OK_SUCCESS = 200;
public static final int BAD_REQUEST = 400;
public static final int UNAUTHORIZED = 401;
public static final int NOT_FOUND = 404;
public static final int INTERNAL_SERVER_ERROR = 500;
private int responseCode;
private String resultContent;
public Result(int responseCode, String resultContent) {
this.responseCode = responseCode;
this.resultContent = resultContent;
}
public int getResponseCode() {
return this.responseCode;
}
public String getResultContent() {
return this.resultContent;
}
public static Result error() {
return new Result(COMMUNICATION_ERROR, "ERROR");
}
}
我的活动中的代码与此相关:
String strBase64 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
int id = 1;
ImageDTO imdto = new ImageDTO(Integer.toString(id), strBase64);
RestClient client = new RestClient();
String jsonDTO = new Gson().toJson(imdto);
Log.i("Pablo", jsonDTO);
Result result = client.put(SERVICE_URL, jsonDTO);
if (result.getResponseCode() != 200) Log.i("****************", "Oups! Smth went wrong!!!");
else Log.i("****************", "Response = 200 , Connection Established :D");
我的应用程序在此行中的RestClient.java中失败:
HttpResponse response = client.execute(request);
我不知道它失败的原因,因为RestClient和Result文件在其他项目中工作正常。
此外,我必须说明在IntelliJ Idea中未完整显示Base64代码。如果我询问最新的char,它是正确的,但它无法在日志模式下显示所有这些。
这是显示失败的日志:
ERROR/AndroidRuntime(27028): FATAL EXCEPTION: main
Process: edu.gvsu.cis.masl.camerademo, PID: 27028
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {edu.gvsu.cis.masl.camerademo/edu.gvsu.cis.masl.camerademo.MyCameraActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3365)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3408)
at android.app.ActivityThread.access$1300(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at edu.gvsu.cis.masl.camerademo.RestClient.executeRequest(RestClient.java:61)
at edu.gvsu.cis.masl.camerademo.RestClient.executeRequest(RestClient.java:46)
at edu.gvsu.cis.masl.camerademo.RestClient.put(RestClient.java:33)
at edu.gvsu.cis.masl.camerademo.MyCameraActivity.onActivityResult(MyCameraActivity.java:78)
at android.app.Activity.dispatchActivityResult(Activity.java:5423)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3361)
... 11 more
答案 0 :(得分:3)
引起:android.os.NetworkOnMainThreadException
原因: 应用程序尝试在其主线程上执行网络操作时引发的异常。
仅针对Honeycomb SDK或更高版本的应用程序进行此操作。针对早期SDK版本的应用程序可以在其主要事件循环线程上进行联网,但是非常不鼓励。
有关详细信息,请参阅NetworkOnMainThreadException。
问题:
您正在Main thread (UI thread)
中执行与网络相关的任务/操作。
<强>解决方案:强>
它应该在worker thread
中完成。
在这种情况下,你可以使用android提供的AsyncTask
。
使用doInbackground
的{{1}}方法执行所有与网络相关的任务。
注意:
您还可以使用AsyncTask
。
StrictMode
是一个开发人员工具,可以检测您可能意外发生的事情,并引起您的注意,以便您可以修复它们。
StrictMode
最常用于捕获应用程序主线程上的意外磁盘或网络访问,其中接收UI操作并进行动画制作。保持磁盘和网络操作不在主线程上,可以使应用程序更加顺畅,响应更快。通过保持应用程序的主线程响应,您还可以阻止向用户显示StrictMode
。
有关详细信息,请参阅StrictMode。