Send HTTP Post with querystring in URL - java

I have doubts about send HTTP Post using querystring.
I have the follow code below but thie code not working. I try send by web service the user and password, embedded in URL, but it not working. this code cannot connect on web-service.
#Override
protected String doInBackground(String... params) {
String result = "";
try {
URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user="+user+"&senha="+password);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
result = response.toString();
bufferedReader.close();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}
return result;
}

I think you mean GET request not POST,
and you should encode the variables in the query params, "user" and "password" in your case.
URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user=" + URLEncoder.encode(user, "UTF-8")+"&senha="+ URLEncoder.encode(password, "UTF-8"));

Related

My code supported with http but not with the https. It shows that java.net.SocketException: Unexpected end of file from server

I tried to send a GET request to the server(containing the details about the devices) and take the response from it. Inside the response should be the details about the devices. Those details are device Id and device Type.
Follow is my code.
I had replaced the Id address by using xxx.xx... sorry about it.
I tried once in http port(8482).
This implementations is works for it. But actually I want to use this program for https port(8120)
Then what should I do for this code to taken the support of https
void callConfigEndPoint() {
String host = "xxx.xxx.xxx.xxx";
String httpPort = "8482";
String deviceToken = "7645221";
String USER_AGENT = "Mozilla/5.0";
String endpointUrl = "http://"+host+":"+httpPort+"/api/device-mgt-config/v1.0";
try {
URL urlObject = new URL(endpointUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlObject.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("token", deviceToken);
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jsonObj = new JSONObject(response.toString());
String deviceId = jsonObj.get("deviceId").toString();
String deviceType = jsonObj.get("deviceType").toString();
System.out.println("deviceId =>" + deviceId);
System.out.println("deviceType =>" + deviceType);
} catch (IOException e) {
e.printStackTrace();
}
}
Please consider that, I had removed the import section from this

Http post request parameters limit

I'm try to pass 19(images) parameters to htttp post request, but when I put more then 9 params, my app don't do the upload to server, I recheck all the code and is ok, server side is ok also.
#Override
protected String doInBackground(Void... params) {
Log.d("SETIMAGE", "IMAGEM DOINBACKGROUND INIT");
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_ID,id);
param.put(KEY_CHAMADO,chamado);
param.put(FACHADA,imageFachada);
param.put(RADIO,imageRadio);
param.put(SUPORTE,imageSuporte);
param.put(MASTRO,imageMastro);
param.put(ISOLAMENTO,imageIsolamento);
param.put(INFRAEXT1,imageInfraExt1);
param.put(INFRAEXT2,imageInfraExt2);
param.put(INFRAINT1,imageInfraInt1);
param.put(INFRAINT2,imageInfraInt2);
param.put(CONECTOREXT,imageConectorExt);
param.put(CONECTORINT,imageConectorInt);
param.put(SALATEC,imageSalaTec);
param.put(RACK,imageRack);
param.put(IDU,imageIDU);
param.put(TOMADAIDU,imageTomadaIDU);
param.put(AZIMUTE,imageAzimute);
param.put(GPS,imageGPS);
param.put(MTCABOEXT,imageMtCaboExt);
param.put(MTCABOINT,imageMtCaboInt);
String result = rh.sendPostRequest(UploadUrl, param);
Log.d("RESULT", result);
return result;
}
This is via RequestHandler.class
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(150000);
conn.setConnectTimeout(150000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null) {
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
I need to pass all images to upload to server. But it's ok only when I pass 9 param.put
You should consider using Retrofit, which allows to upload huge size files in chunks and has more flexibility than most libraries.

HttpURLConnection - Response Code: 400 (Bad Request) Android Studio -> xserve

So I'm trying to connect to our database via Xserve, AT the moment I'm trying to access the token for the user. I'm using the correct username and password along with the context type and grant type; I know this because I've tried the same POST method via googles postmaster extension. For whatever reason when I try the same thing on Android, at least what I think is the same, it gives me a 400 response code and doesn't return anything.
Here's the code used to connect:
private HttpURLConnection urlConnection;
#Override
protected Boolean doInBackground(Void... params) {
Boolean blnResult = false;
StringBuilder result = new StringBuilder();
JSONObject passing = new JSONObject();
try {
URL url = new URL("http://xserve.uopnet.plymouth.ac.uk/modules/INTPROJ/PRCS251M/token");
// set up connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// set up parameters to pass
passing.put("username", mEmail);
passing.put("password", mPassword);
passing.put("grant_type", "password");
// add parameters to connection
OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(passing.toString());
// If request was good
if (urlConnection.getResponseCode() == 200) {
blnResult = true;
BufferedReader reader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
}
//JSONObject json = new JSONObject(builder.toString());
Log.v("Response Code", String.format("%d", urlConnection.getResponseCode()));
Log.v("Returned String", result.toString());
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return blnResult;
}
I haven't stored the result into the JSONObject yet as I'll use that later, but I expected some kind of output via the "Log.v".
Is there anything that stands out?
try {
URL url = new URL("http://xserve.uopnet.plymouth.ac.uk/modules/INTPROJ/PRCS251M/token");
parameters = new HashMap<>();
parameters.put("username", mEmail);
parameters.put("password", mPassword);
parameters.put("grant_type", "password");
set = parameters.entrySet();
i = set.iterator();
postData = new StringBuilder();
for (Map.Entry<String, String> param : parameters.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
postDataBytes = postData.toString().getBytes("UTF-8");
// set up connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
urlConnection.setRequestMethod("POST");
urlConnection.getOutputStream().write(postDataBytes);
// If request was good
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
}
Log.v("Login Response Code", String.valueOf(urlConnection.getResponseCode()));
Log.v("Login Response Message", String.valueOf(urlConnection.getResponseMessage()));
Log.v("Login Returned String", result.toString());
jsonObject = new JSONObject(result.toString());
token = jsonObject.getString("access_token");
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
if (token != null) {
jsonObject = driverInfo(token);
}
}
this works, although I've moved it to it's own function now.
changed the input type to a HashMap

Flask not receiving POST from Android

I used to use DefaultHttpClient for my networking code, but decided to change to HttpURLConnection.
I have searched for other questions on how to send POST messages (eg How to add parameters to HttpURLConnection using POST), but for some reason my Flask app always gives me error 400.
When I use logcat, it indeed displays that my POST message is "username=asdf&password=asdf". I include the code below. Also, if I initialized the cookieManager in the method that called this method (makeServiceCall), will returning cookieManager keep my session for subsequent calls to makeServiceCall?
public CookieManager makeServiceCall(CookieManager cookieManager, String urlString, int method, List<NameValuePair> db) {
String charset = "UTF-8";
try {
URL url = new URL(urlString);
if (method == POST) {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (db != null) {
try {
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept-Charset", charset);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(out, charset));
Log.d("log", "> " + getQuery(db));
writer.write(getQuery(db));
writer.flush();
writer.close();
out.close();
//Get Response
InputStream in = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.d("Read attempt: ", "> " + response.toString());
}
finally {
urlConnection.disconnect();
}
}
}
etc.
Flask code:
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error=error)

Sending post request to https

I need to send a post request to a https address. I have a function that sends post messages currectly but i cant seem to make it work for https.
public static String serverCall(String link, String data){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = data;
try
{
url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
return response;
}
i have tryed using HttpsURLConnection insted of HttpURLConnection, i am still getting null from my server.
you should call connect();
....
connection.setRequestMethod("POST");
connection.connect();
....

Categories