要将数据发布到服务器,我使用以下方法,成功发布到服务器,这里我需要获取一个注册ID号码。我已经在服务器php中编码了。我试过Postman工作得很好,但在这里我没有得到。那么请让我知道我要做什么?
static String result=null;
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v("TWA CLIENT REPORT", "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
答案 0 :(得分:0)
试试这个片段,我会为你工作,
URL url;
url = new URL("http://www.url.com/app.php");
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httppost = (HttpURLConnection) connection;
httppost.setDoInput(true);
httppost.setDoOutput(true);
httppost.setRequestMethod("POST");
httppost.setRequestProperty("User-Agent", "Tranz-Version-t1.914");
httppost.setRequestProperty("Accept_Language", "en-US");
httppost.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
DataOutputStream dos = new DataOutputStream(httppost.getOutputStream());
dos.write(b); // bytes[] b of post data
String reply;
InputStream in = httppost.getInputStream();
StringBuffer sb = new StringBuffer();
try {
int chr;
while ((chr = in.read()) != -1) {
sb.append((char) chr);
}
reply = sb.toString();
} finally {
in.close();
}