[java]代码库
package com.example.day04_httpurlconnection_post;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.google.gson.Gson;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private ListView listView;
// String path = "http://v.juhe.cn/nba/all_team_info.php?";
String key = "cardno=142430199610040813&dtype=json&key=775e7862878f435b55d424622b6143e2";
String path = "http://apis.juhe.cn/idcard/index?";
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
Bean bean = (Bean) msg.obj;
listView.setAdapter(new ArrayAdapter<Result>(MainActivity.this,
android.R.layout.simple_list_item_1, bean.result));
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
}
public void button(View v) {
new Thread() {
public void run() {
getData();
};
}.start();
}
// 获取网络数据
protected void getData() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
// post方式请求
connection.setRequestMethod("POST");
connection.setReadTimeout(5000);
// 连接
connection.connect();
// 得到输出流,给服务器传参数
OutputStream outputStream = connection.getOutputStream();
outputStream.write(key.getBytes());
if (connection.getResponseCode() == 200) {
StringBuilder builder = new StringBuilder();
//得到服务器返回的信息
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new
InputStreamReader(inputStream));
String s;
// 记录每一行读取到的信息,当等于null时,不在循环
while ((s = bufferedReader.readLine()) != null) {
// 记录每一行的信息
builder.append(s);
}
String string = builder.toString();
Log.d("logd", "" + string);
// /////////////////////////////////////////////////////////////////
/* Gson gson = new Gson();
Bean bean = gson.fromJson(new InputStreamReader(inputStream), Bean.class);
// 发送给handler
Message msg = Message.obtain();
msg.obj = bean;
handler.sendMessage(msg);*/
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
初级程序员
by: 云代码会员 发表于:2017-06-04 15:19:54 顶(0) | 踩(0) 回复
谢谢
回复评论