package com.example.Demo_9;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
private Button button;
private String result="";
private Handler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
final TextView textView = (TextView) findViewById(R.id.text);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
send();
Message m = handler.obtainMessage();
handler.sendMessage(m);
}
}).start();
}
});
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (result != null) {
textView.setText(result);
}
super.handleMessage(msg);
}
};
}
public void send() {
String target = "http://192.168.1.161:8080/blog/demo.json";
HttpClient client = new DefaultHttpClient();
HttpPost requet = new HttpPost(target);
HttpResponse response;
try {
response = client.execute(requet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
} else {
result = "connection failed!"; //
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
刚开始写这个,怎么老是得到 result = "connection failed!"; 呢? 手机能够连接到tomcat服务器的demo.json文件的,这没问题的。我哪里逻辑错了吗?我想把json文件内容显示到textview上的....
巴扎黑2017-04-17 15:03:20
每次看到有人用HttpClient我就是想先说:Google已经抛弃HttpClient了,6.0里已经把HttpClient库删除了,那么去解决你的问题还有意义吗?等把你的问题解决好了,你又怎么去解决版本兼容的问题呢?
先换了HTTP请求库再说吧。
ringa_lee2017-04-17 15:03:20
伪代码大致如下:
final HttpPost httpPost = new HttpPost(url);
final List<NameValuePair> requestParams = new ArrayList<NameValuePair>();
HashMap<String, Object> paramsMap = new HashMap<String, Object>();
paramsMap.put("param", param);
requestParams.add(new BasicNameValuePair("body", params.to));
new Thread((new Runnable() {
@Override
public void run() {
try {
httpPost.setEntity(new UrlEncodedFormEntity(requestParams, ConstantsValue.ENCODING));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
}
mHandler.sendMessage(Message.obtain(mHandler, tag));
};
})).start();
最好自定义一个线程池,ThreadPoolExecutor 用起来很方便。
不过网络请求还是用 OkHttp 或者 Retrofit 吧,很方便的。