知识AndroidAndroid-HttpRequest
Kahvia POST
据度娘解释,以前的安卓应用发出 http 请求后,如果请求时间过长,就会产生应用无响应的状态。所以改成了现在这种,直接发出 http 请求就会抛出错误。想要正确地发出http请求,就需要开一个子线程来进行这些操作。
下方的代码采用的是,直接通过 Thread 类创建子线程,需要传递的参数是一个实现了 Runnable 接口的类的实例对象。这里的对象通过匿名类生成。线程和匿名类的知识,可以在《Java2 实用教程》(俗称 课本)中找到。
线程的启动使用 start()方法。启动后,就进入等待cpu使用权的队列。得到使用权就开始运行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| public class HttpUtil { public static String requestPost() throws IOException, JSONException { new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://www.xxx.com/user/check"); HttpURLConnection connection= (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); connection.setRequestProperty("Accept","application/json"); connection.setDoOutput(true); connection.setDoInput(true);
User user=new User("914302063","123456"); JSONObject jsonObject=new JSONObject(user.toString()); String json=jsonObject.toString(); Log.i("JsonData",json);
OutputStream outputStream=connection.getOutputStream(); outputStream.write(json.getBytes()); outputStream.flush(); outputStream.close(); Log.i("responseCode", String.valueOf(connection.getResponseCode()));
InputStream inputStream=connection.getInputStream(); String result=""; StringBuilder stringBuilder=new StringBuilder(); InputStreamReader inputStreamReader=new InputStreamReader(inputStream); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); while((result=bufferedReader.readLine())!=null){ stringBuilder.append(result); } Log.i("resultData", String.valueOf(stringBuilder)); }catch (Exception e){ System.out.println(e); } } }).start();
return null; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class User { String username; String password;
public User(){} public User(String username, String password) { this.username = username; this.password = password; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
@Override public String toString() { return "{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
|