Http post request parameters limit - java

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.

Related

Java HTTPURLConnection - Reading error response from code 400 with payload

I am trying to call an API that gives 400 on some requests.
But it has meaningful message that needs to be read.
Also i am passing a payload(json body) in the api call
My code(it takes a payload as json) and the 400 response is below
I am able to successfully read the response of 200 but issue is with 400
public static void blahblah (String input, String CustomerID, String endpoint, String dateNameFolder) throws UnknownHostException
{
try {
URL url = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
File fileObj = new File(CustomerID + ".json");
if (!fileObj.exists()) {
fileObj.createNewFile();
FileWriter dataWriter = new FileWriter(CustomerID + ".json");
dataWriter.write(sb.toString());
dataWriter.close();
} else {
FileWriter dataWriter = new FileWriter(CustomerID + ".json");
dataWriter.write(sb.toString());
dataWriter.close();
}
conn.disconnect();
}catch (MalformedURLException e) {
l
log.info(e);
}
catch (IOException e) {
log.error("Error in Validating Request to Catalog for Customer ID(400 Bad Request) : " + CustomerID ) ;
log.info(e);
}
}
Sample output of 400 bad request :
<Response>
<StatusCode>BadRequest</StatusCode>
<ErrorCode>OrderRequestInvalid.InvalidCharacteristicUse</ErrorCode>
<Message>Characteristic ID cannot be found in the specification: { EntityUniqueCode: CS_0aefdfec-022e-4ac9-a84b-83c8ea2e0fd0, CharacteristicID: 76c4e767-ce7b-4675-a178-d832839b322f}</Message>
<Context>
<EntityUniqueCode>CS_0aefdfec-022e-4ac9-a84b-83c8ea2e0fd0</EntityUniqueCode>
<CharacteristicID>76c4e767-ce7b-4675-a178-d832839b322f</CharacteristicID>
</Context>
</Response>
You need to choose correct stream depending on your response status. here is an example how you can do this:
BufferedReader br = null;
int statusCode = conn.getResponseCode();
if (statusCode>299){
br = new BufferedReared(new InputStreamReader(conn.getErrorStream()));
} else {
br = new BufferedReared(new InputStreamReader(conn.getInputStream()));
}

Android cannot read http post response from flask server

I just wrote a simple server with flask and send a http post requset to the server from an Android App. But I failed to read the response in the Android App. The app throw an exception:
My flask code is:
#app.route('/zsj',methods = ['POST'])
def show_data():
data = request.get_json()
print request.values #json.loads(data)#request.get_json()
#data = json
#print data
return "aaaa"#jsonify({'w':'u'})
My android App just use the HttpURLConnection class to send a post and get a respones from the server, which is expected as a string: 'aaaa'. We tried to read out the string but failed.
And my Android code is
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
// Connect to the server
URL url = new URL("http://ec2-35-164-172-186.us-west-2.compute.amazonaws.com:5000/zsj");
JSONObject postDataParams = new JSONObject();
// Display command
postDataParams.put("Weather", "email");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
responseMessage = conn.getResponseMessage();
int responseCode=conn.getResponseCode();
responseCode2=responseCode;
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
// jtest=conn.getInputStream().read(data);
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
StringBuffer sb = new StringBuffer("");
String line="";
StringBuffer sb2 = new StringBuffer("");
// in.readLine();
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
// jtest="abc";
// jtest=sb.toString();
while((line = er.readLine()) != null) {
sb2.append(line);
break;
}
in.close();
er.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
My App code just throw an exception at
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
Anyone knows how to solve the problem

HttpURLConnection- post xml and url parameters as separate entities

Exisitng code :
Sending id and pass in url and xml data in body
String url = http://localhost:8080/FirstServlet/MyFirstServletMapping&id=123&pass=sDff
HttpURLConnection urlc = (HttpURLConnection) new URL(url).openConnection();
urlc.setDoOutput(true);
urlc.setRequestMethod("POST");
OutputStream out = urlc.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write("<xml>");
writer.flush();
writer.close();
Now I need to change the code to send id and pass also in POST.
How can i change the code to add id and pass in POST and do not break the server read.
I tried as below but am seeing xml is getting appended at end of pass.
Will this cause any issue at server side? Or this looks fine?..Any suggestions please?
New Code:
String url = "http://localhost:8080/FirstServlet/MyFirstServletMapping";
HttpURLConnection urlc = (HttpURLConnection) new URL(url).openConnection();
urlc.setDoOutput(true);
urlc.setRequestMethod("POST");
OutputStream out = urlc.getOutputStream();
byte[] postData = setRequestData(111124l, "password5");
out.write(postData);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write("xml");
writer.flush();
writer.close();
private static byte[] setRequestData(Long prsId, String password) throws IOException {
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("id", prsId);
params.put("pass", password);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0)
postData.append('&');
try {
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
System.out.println("post data is--->"+postData.toString());
return postDataBytes;
}
Output:
in post method
dsid-->111124
password is-->password5xml
Served at: /FirstServlet: end

Send HTTP Post with querystring in URL

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"));

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