Sending a parameterized HTTP POST request from Android
问题:
我无法从Android设备访问云数据。我正在使用POST方法,并且期望JSON响应。我相信我收到403(禁止)错误。但是我可以使用curl访问相同的数据。因此,我认为自己做错了,因此寻求他人的帮助。
背景
这是我要复制的curl命令字符串。我收到对该命令的有效响应。
1 | curl -X POST --data"token={String}¶m1={int}¶m2={int}" https://www.example.com/api/dir1/dir2" |
下面是android代码。
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 | String post_url ="https://www.example.com/api/dir1/dir2"; Thread thread = new Thread(new Runnable() { public void run() { try { String urlParameters ="token={Key-string}¶m1={int}¶m2={int}"; byte[] postData = urlParameters.getBytes(); int postDataLength = postData.length; URL url = new URL(post_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept","application/json"); conn.setRequestProperty("charset","utf-8"); conn.setRequestProperty("Content-Length",Integer.toString(postDataLength)); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); OutputStream os = conn.getOutputStream(); os.write(urlParameters.toString().getBytes("UTF-8")); os.close(); InputStream stream = conn.getInputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(stream )); String data = null; StringBuffer response = new StringBuffer(); while ((data = in.readLine()) != null) { response.append(data);} in.close(); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); |
参考文献:
- POST请求发送json数据java HttpUrlConnection
- 从Android发送JSON HTTP POST请求
- Java-通过POST方法轻松发送HTTP参数
- 应用程序/ x-www-form-urlencoded还是multipart / form-data?
- 如何使用POST向HttpURLConnection添加参数
- JSON解析,创建URLConnection-Android Studio
您可以尝试使用Postman(Google chrome插件)拨打电话,然后单击"代码"链接。邮递员将以多种语言向您生成请求,例如PHP,java,C等。
例如:
添加到您的gradle:
1 | compile 'com.squareup.okhttp3:okhttp:3.5.0' |
在某处打电话:
1 2 3 4 5 | new Thread() { public void run() { makeCall(); } }.start(); |
创建该类:
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 | public void makeCall() { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType,"{\ "param1":"data1"}"); Request request = new Request.Builder() .url("https://your_url_here") .post(body) .addHeader("content-type","application/json") .addHeader("cache-control","no-cache") .build(); try { Response response = client.newCall(request).execute(); Log.e("okmsg1", response.toString()); Log.e("okmsg2", response.message()); Log.e("okmsg3", response.body().string()); } catch (IOException e) { Log.e("err", e.getMessage()); } } |