[英]HttpurlConnection Post Request body php server?
我的服務器帶有文件。 php
好,我想用我的應用程序向服務器發送發布request
,我試圖這樣做,但是當我在郵遞員上嘗試服務器時,我總是收到“”
{“結果”:“ jfYRsbW17HA3bHtaJdDm”,“ errorMessage”:“錯誤”}
我希望我的應用在發送Post Request時看到這些,這是我的代碼:(為什么我會得到null)
public class HttpParoonakRequest {
public static String HttpParoonakRequestGetUrl(){
URL url ;
HttpURLConnection client = null;
try {
url = new URL("myphp");
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.setRequestProperty("method","get_random_wallpaper");
client.setDoInput(true);
client.setDoOutput(true);
client.connect();
DataOutputStream wr = new DataOutputStream (
client.getOutputStream ());
wr.flush ();
wr.close ();
//Get Response
InputStream is = client.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\n');
}
Log.d("hey",response.toString());
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
finally {
if(client != null) // Make sure the connection is not null.
client.disconnect();
}
}
並在另一個活動中以這種方式調用它:
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
String abcd = HttpParoonakRequest.HttpParoonakRequestGetUrl();
System.out.println("Message1 "+ abcd);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
});
thread.start();
您通過錯誤的方式傳遞參數:您應將client.setRequestProperty("method","get_random_wallpaper")
替換為client.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
並通過wr
流在請求正文中傳遞您的參數,如下所示:
...
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
client.setDoInput(true);
client.setDoOutput(true);
client.connect();
DataOutputStream wr = new DataOutputStream(
client.getOutputStream());
wr.write("method=get_random_wallpaper".getBytes());
wr.flush();
wr.close();
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.