I have server with a file. php
well I want to send post request
to the server with my app I'm trying to do that but I always got "" when i try my server on postman i get
{"result": "jfYRsbW17HA3bHtaJdDm", "errorMessage": "error"}
I want my app to see those when i send Post Request here is my code : (why i am getting 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();
}
}
and call it this way in another activity:
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();
You pass parameters by wrong way: You should replace client.setRequestProperty("method","get_random_wallpaper")
by client.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
and pass your parameter in request body via wr
stream like this:
...
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();
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.