[英]Sending a parameterized HTTP POST request from Android
题:
我无法从Android设备访问云数据。 我正在使用POST方法,并且期望JSON响应。 我相信我收到403(禁止)错误。 但是我可以使用curl访问相同的数据。 所以我相信我做错了,因此寻求别人的帮助。
背景
这是我要复制的curl命令字符串。 我收到对该命令的有效响应。
curl -X POST --data "token={String}¶m1={int}¶m2={int}" https://www.example.com/api/dir1/dir2"
以下是android代码。
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();
参考文献:
您可以尝试使用Postman(Google Chrome插件)拨打电话,然后单击“代码”链接。 邮递员会以多种语言向您生成请求,例如PHP,java,C等。
例如:
添加到您的gradle:
compile 'com.squareup.okhttp3:okhttp:3.5.0'
在某处打电话:
new Thread() {
public void run() {
makeCall();
}
}.start();
创建该类:
public void makeCall() {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n \"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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.