HttpURLConnection to send POST data gives error - java

I'm using this script to try to send POST data to a PHP script from my Android app. But it doesn't even let me Run it due to the error "loginUrl cannot be resolved". Since other people seem to have got this code working, have I missed something obvious here? Here's the code but changed by me (see it with comments by the link above):
public void postData() {
URL url;
HttpURLConnection conn;
try{
url=new URL("http://mysite/test.php");
String param="param1=" + URLEncoder.encode("value1","UTF-8")+
"&param2="+URLEncoder.encode("value2","UTF-8")+
"&param3="+URLEncoder.encode("value3","UTF-8");
conn=(HttpURLConnection)loginUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.close();
String response= "";
Scanner inStream = new Scanner(conn.getInputStream());
while(inStream.hasNextLine())
response+=(inStream.nextLine());
}
catch(MalformedURLException ex){
Toast.makeText(GameButton.this, ex.toString(), 1 ).show();
}
catch(IOException ex){
Toast.makeText(GameButton.this, ex.toString(), 1 ).show();
}
}
Thanks!

You have declared the variable as url but you are trying to use it as loginUrl.
Check these declaration and initilization in your code
URL url;
url=new URL("http://mysite/test.php");
and problem here when you try to open the connection:
conn=(HttpURLConnection)loginUrl.openConnection();
it should be
conn=(HttpURLConnection)url.openConnection();

Related

unexcepted end of stream on Connection

I am doing a Android app and trying to input a new data into the student database, the connection which is HttpURLConnection is ok. I got a problem which says: java.io.IOException: unexcepted end of stream on Connection {....(here is my host address}.
I think the main problem is the conn.getOutputStream(), and I have check that the stream is not closed.
public static void createUser(Student user){
//initialise
URL url = null;
HttpURLConnection conn = null;
final String methodPath="/friendfinder.student/";
try {
Gson gson =new Gson();
String stringUserJson=gson.toJson(user);
url = new URL(BASE_URI + methodPath);
//open the connection
conn = (HttpURLConnection) url.openConnection();
//set the timeout
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
//set the connection method to POST
conn.setRequestMethod("POST");
//set the output to true
conn.setDoOutput(true);
//set length of the data you want to send
conn.setFixedLengthStreamingMode(stringUserJson.getBytes().length);
//add HTTP headers
conn.setRequestProperty("Content-Type", "application/json");
//Send the POST out
PrintWriter out= new PrintWriter(conn.getOutputStream());
out.print(stringUserJson);
out.close();
Log.i("error",new Integer(conn.getResponseCode()).toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
}
Would someone take a look at my code and give me a suggestion please?

Unexpected status line when making post request from android device

Hi I have an Android app that needs to connect to an API (currently running locally) to authenticate the user, so I'm trying to send a POST request with a JSON object as the request body but whenever I try to login I get the following error:
Unexpected status line: ��
java.net.ProtocolException: Unexpected status line: ��
Here's my code:
String API_URL = "http://10.0.2.2:8443/api/";
try {
URL url = new URL(API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("customerId", 1);
jsonObject.put("password" , mPassword);
jsonObject.put("username" , mEmail);
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
Log.d("REQUEST BODY", jsonObject.toString());
wr.flush();
wr.close();
int response = urlConnection.getResponseCode();
Log.d("RESPONSE", String.valueOf(response));
if(response == HttpURLConnection.HTTP_OK) {
InputStream bis = new BufferedInputStream(urlConnection.getInputStream());
return getStringFromInputStream(bis);
}
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
Can anyone please tell me what I might be doing wrong? Thanks!
EDIT
Not sure if this helps but the problem seems to occur when I call urlConnection.getResponseCode();.
Possibly you are recycling the connection
try adding urlConnection.setRequestProperty("Connection", "close"); before connecting

How to display android POST string on PHP server?

I am trying to send json string from my android app to my php server. Below is the complete code from my mobiledb_control.php and httpconnect.java
The Log.v("HTTPSENDER","WORKED"); runs, and I get no errors.
However my error_log("in"); does not run.
How do I display the JSON sent via android into my error_log() ?
HttpConnect.java:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
}catch(Exception e){
e.printStackTrace();
}
}
}
mobiledb_control.php:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/error.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
$headers = apache_request_headers();
?>
try this in PHP code
and turn on error reporting like this
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
and
print_r($_POST);
for more clarification what you are getting from post.
use encode and decode functions of php for making and parsing json.
$request=json_decode($_POST['json']); // it gives the Array
foreach($request as $values){
echo($values['your_value1'])
echo($values['your_value2'])
}
please refer this url : http://php.net/manual/en/function.json-decode.php
Seemed to have fixed it but I have no idea how
PHP File:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/location.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
?>
JAVA File:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
Log.v("HTTPSENDER",""+conn.getResponseCode());
}catch(Exception e){
e.printStackTrace();
}
}
}
In designing server-client communication, it is imperative to make sure both client and server can communicate with each other. With that in mind, can you please provide the server response code by adding this in your code inside try block:
try {
...
Log.d(TAG, "code: " + conn.getReturnCode());
InputStream is = conn.getInputStream();
String serverReply = readIt(is, 500);
Log.d(TAG, serverReply);
...
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
It will return 200 and 401 respectively. Returns -1 if no code can be
discerned from the response (i.e., the response is not valid HTTP).
Cheers!

Download URL in Android

I've tried to download HTML content from the URL http://google.com and another URL.
I tried:
URL url = new URL("http://google.com/");
urlConnection = (HttpURLConnection) url.openConnection();
And although I've tried InputStream, it didn't work the same.
try {
URL url = new URL("http://google.com/");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
System.out.print(urlConnection.getResponseCode());
}
catch (Exception e)
{
System.out.print("Error: "+e.getMessage());
}
finally {
urlConnection.disconnect();
}
At the end I see the catch and the e.getMessage is null. If I debug it, urlConnection.getResponseCode() is returning -1.
You set DoOutput where you will not do output. You do not set DoInput where you do input. Remove the chunked streaming mode.

HTTP URL redirect status code

The url which I give gets redirected. When i hit the url with some browser it redirects to another site. When i test it in some rest client i am getting http code 302, which is correct for redirect. But i try the same with below code, it returns 200. Can somebody help me out ?Thanks in advance.
updated url.
try {
URL url = new URL("https://securestore.hbo.com/cart.php?f=pplogin&ppx=1&method=checkout");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int code = connection.getResponseCode();
System.out.println(connection.getResponseMessage());
System.out.println("code is" + code);
connection.disconnect();
}
catch (MalformedURLException e) {
e.printStacTrace();
}
catch (IOException e) {
e.printStackTrace();
}
If url1 is being redirected to url2, then you will get 302 status. However if you code is directally calling url2, you are bound to get 200.
Try the following code.
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
.....
connection = (HttpConnection)Connector.open(url);
responseCode = connection.getResponseCode();
Try adding a response with the 302 code you want. Something like connection.setStatus(statusCode) I may be wrong though.
The HttpURLConnection will follow the redirects by default.
Try setting the following if you do not wish to follow redirects:
HttpURLConnection.setFollowRedirects(false);
For example, in relation to your code:
try {
URL url = new URL("");
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int code = connection.getResponseCode();
System.out.println(connection.getResponseMessage());
System.out.println("code is" + code);
connection.disconnect();
}
catch (MalformedURLException e) {
e.printStacTrace();
}
catch (IOException e) {
e.printStackTrace();
}

Categories

Resources