Android Get Post 请求
线程加载获得json对象
1 //线程中或intentService加载执行请求 2 3 4 package com.example.administrator.mylogin; 5 import android.app.IntentService; 6 import android.content.Intent; 7 import android.content.Context; 8 import android.util.Log; 9 import android.widget.Toast; 10 import com.example.administrator.mylogin.Dao.dao; 11 import com.example.administrator.mylogin.Dao.imol.LoginImpl; 12 import java.util.HashMap; 13 import java.util.Map; 14 public class MyIntentService extends IntentService { 15 16 final String KEY="http://api.dongman.fm/account/loginByAccountAndPwd"; 17 public MyIntentService() { 18 super("MyIntentService"); 19 } 20 21 @Override 22 protected void onHandleIntent(Intent intent) { 23 dao dao= new LoginImpl(); 24 String user=intent.getStringExtra("username"); //获得参数 25 String pswd=intent.getStringExtra("password"); //获得参数 26 27 Map map= new HashMap<String,String>(); //设置map 28 map.put("account",user); //传入参数 29 map.put("password",pswd); 30 String json=dao.postDownloadJson(KEY,map); //填写URL 和请求参数 31 32 Log.i("Json",json); 33 } 34 35 }
发送Post请求实现方法
1 package com.example.administrator.mylogin.Dao.imol; 2 3 import android.util.Log; 4 5 import com.example.administrator.mylogin.Dao.dao; 6 import com.example.administrator.mylogin.model.user; 7 8 import org.json.JSONException; 9 import org.json.JSONObject; 10 11 import java.io.BufferedInputStream; 12 import java.io.BufferedReader; 13 import java.io.ByteArrayOutputStream; 14 import java.io.DataOutputStream; 15 import java.io.IOException; 16 import java.io.InputStream; 17 import java.io.InputStreamReader; 18 import java.io.PrintWriter; 19 import java.net.HttpURLConnection; 20 import java.net.MalformedURLException; 21 import java.net.URL; 22 import java.net.URLEncoder; 23 import java.util.HashMap; 24 import java.util.Map; 25 26 /** 27 * Created by Administrator on 2017/12/5. 28 */ 29 30 31 /** 32 * 获取登录的json 33 */ 34 public class LoginImpl implements dao { 35 @Override 36 public String postDownloadJson(String path, Map<String, String> keyAndValues) { 37 URL url = null; //url 38 HttpURLConnection conn=null; 39 ByteArrayOutputStream baos = null; 40 try { 41 url = new URL(path); //对象创建 42 conn= (HttpURLConnection) url.openConnection(); //创建链接对象,强转对象打开链接 43 conn.setRequestMethod("POST"); //设置请求类型(大写) 44 // conn.setConnectTimeout(10000); //连接超时 单位毫秒 45 // conn.setReadTimeout(2000); //读取超时 单位毫秒 46 47 conn.setUseCaches(false); 48 // 发送POST请求必须设置如下两行 49 conn.setDoInput(true); 50 conn.setDoOutput(true); 51 //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据 52 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 53 conn.connect(); //打开连接 54 //获取url对应的输出流 55 PrintWriter print = new PrintWriter(conn.getOutputStream());//设置输出流 56 StringBuilder builder = new StringBuilder(); //用map设置key值 57 for (Map.Entry<String, String> entry : keyAndValues.entrySet()) { 58 builder.append(entry.getKey()); 59 builder.append("="); 60 builder.append(entry.getValue()); 61 builder.append("&"); 62 } 63 builder.substring(0, builder.length() - 1); //不显示最后一个& 64 String parameters = URLEncoder.encode(builder.toString(), "UTF-8"); 65 66 print.write(parameters); //设置key 发出请求 67 // flush输出流的缓冲 68 print.flush(); 69 70 //开始获得数据 71 InputStream bis = conn.getInputStream(); //获得输出流 72 baos = new ByteArrayOutputStream(); 73 int len; 74 75 byte[] b = new byte[2048]; 76 while ((len = bis.read(b)) != -1) { 77 baos.write(b, 0, len); 78 } 79 baos.flush(); 80 return new String(baos.toByteArray()); //返回字符串 81 82 } catch (IOException e) { 83 e.printStackTrace(); 84 } finally { 85 try { 86 if (baos != null) baos.close(); 87 } catch (IOException e) { 88 e.printStackTrace(); 89 }finally { 90 if(conn!=null){ 91 conn.disconnect(); //关闭连接 92 } 93 } 94 } 95 return null; 96 } 97 98 @Override 99 public user postUserLoginInfo(String json) { 100 JSONObject jsonObg; 101 user user = new user(); 102 try { 103 jsonObg = new JSONObject(json); 104 jsonObg.getString("message"); 105 JSONObject jsonDate = jsonObg.getJSONObject("data"); 106 user.setAvatar_url(jsonDate.getString("avatar_url")); 107 user.setName(jsonDate.getString("name")); 108 user.setToken(jsonDate.getString("refresh_token")); 109 } catch (JSONException e) { 110 e.printStackTrace(); 111 } 112 return user; 113 } 114 116 public void aaa() { 117 Map kvMap = new HashMap<String, String>(); 118 kvMap.put("username", "aaa"); 119 kvMap.put("password", "123"); 120 postDownloadJson("http://baidu.com", kvMap); 121 } 122 123 public void readContentFromPost() throws IOException { 124 // Post请求的url,与get不同的是不需要带参数 125 URL postUrl = new URL("http://api.dongman.fm/account/loginByAccountAndPwd"); 126 // 打开连接 127 HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); 128 129 // 设置是否向connection输出,因为这个是post请求,参数要放在 130 // http正文内,因此需要设为true 131 connection.setDoOutput(true); 132 // Read from the connection. Default is true. 133 connection.setDoInput(true); 134 // 默认是 GET方式 135 connection.setRequestMethod("POST"); 136 137 // Post 请求不能使用缓存 138 connection.setUseCaches(false); 139 140 connection.setInstanceFollowRedirects(true); 141 142 // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 143 // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode 144 // 进行编码 145 connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 146 // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, 147 // 要注意的是connection.getOutputStream会隐含的进行connect。 148 connection.connect(); 149 DataOutputStream out = new DataOutputStream(connection 150 .getOutputStream()); 151 // The URL-encoded contend 152 // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致 153 String content = "account=" + URLEncoder.encode("123@qq.com", "UTF-8"); 154 content +="&password="+URLEncoder.encode("1", "UTF-8");; 155 // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面 156 out.writeBytes(content); 157 158 out.flush(); 159 out.close(); 160 161 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 162 String line; 163 164 while ((line = reader.readLine()) != null){ 165 Log.i("Log-----------",line); 166 } 167 168 reader.close(); 169 connection.disconnect(); 170 } 171 172 }