运用HttpClient方式上传图片时出错
代码如下:
// 运用第三方jar包HttpClient进行上传
private void uploadHttpClient() {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity muti = new MultipartEntity();
File parent = Environment.getExternalStorageDirectory();
File fileAbs = new File(parent, "one.png");
FileBody fileBody = new FileBody(fileAbs);
muti.addPart("file", fileBody);
post.setEntity(muti);
try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
-------------------------
public class UploadActivity extends AppCompatActivity {
private Button mButton;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
mButton = (Button) findViewById(R.id.btn);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
File file = Environment.getExternalStorageDirectory();
File fileAbs = new File(file,"one.png");
String fileName=fileAbs.getAbsolutePath();
String url = "http://192.168.23.4:8080/Upload";
UploadThread thread = new UploadThread(fileName,url);
thread.start();
}
});
}
}