我正在尝试从我的安卓手机向我的本地网络服务器发送一张图片。一旦它连接到网络服务器,我得到以下信息:android.os.NetworkOnMainThreadException
我认为我的问题的解决方案是使方法异步。这是我不熟悉的事情。
所以我的问题是:如何使以下方法异步?
public class Send {
public Send(){
}
public static String send(String path) throws Exception {
String filePath = path;
String svar;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("path to web server");
FileBody pic = new FileBody(new File(filePath));
MultipartEntity requestEntity = new MultipartEntity();
requestEntity.addPart("file", pic);
httppost.setEntity(requestEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte [] responseBody = outstream.toByteArray();
svar = new String(responseBody);
System.out.println(svar);
} finally {
try {
httpclient.getConnectionManager().shutdown();
}
catch (Exception ignore) {
}
}
return svar;
}
}