(GET http request) How send cookie in the server - java

I'm trying to send cookies to the server, but it doesn't work. Please tell me thats wrong. Here is my code.
At first, I take cookie in the POST request.
> Map <String, List<String>> headerFields = postRequest.getHeaderFields();
> List<String> cookiesHeader = headerFields.get("Set-Cookie");
Later, in the GET request, i'm send cookie to the server.
getRequest.setRequestProperty("Cookie", cookiesHeader.toString());
Help me. I'm beginner, not judge strictly.
Here all my code.
#Override
protected String doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
String store_id = "";
final String COOKIES_HEADER = "Set-Cookie";
final String COOKIE = "Cookie";
try {
Thread.sleep(4000);
Log.i(TAG, "httpRequest start");
String parametrs = mPhone.getText().toString();
String parametrs2 = mPass.getText().toString();
JSONObject allParams = new JSONObject();
HttpURLConnection postRequest = null;
InputStream inputStream = null;
byte[] data = null;
try {
URL serverUrl = new URL("https://api.fianitlombard.ru/mobile/auth");
postRequest = (HttpURLConnection) serverUrl.openConnection();
postRequest.setReadTimeout(10000 /* milliseconds */);
postRequest.setConnectTimeout(15000 /* milliseconds */);
postRequest.setRequestMethod("POST");
postRequest.setDoInput(true);
postRequest.setDoOutput(true);
postRequest.setRequestProperty("Content-Type", "application/json; charset=utf-8");
postRequest.connect();
allParams.put("phone", parametrs);
allParams.put("password", parametrs2);
Log.i(TAG, "allParams" + allParams);
OutputStream bos = (postRequest.getOutputStream());
bos.write(allParams.toString().getBytes());
String helpInfo = postRequest.getResponseMessage();
Log.i(TAG, "helpInfo =" + helpInfo);
responseCode = postRequest.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Map<String, List<String>> headerFields = postRequest.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (responseCode == 200) {
inputStream = postRequest.getInputStream();
byte[] buffer = new byte[8192]; // Такого вот размера буфер
// Далее, например, вот так читаем ответ
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
Log.i(TAG, "responseCode = " + responseCode);
Log.i(TAG, "resultCode = " + resultString);
JSONObject jsonObject = new JSONObject(resultString);
store_id = jsonObject.getString("store_id");
Log.i(TAG, "store_id =" + store_id);
bos.close();
baos.close();
postRequest.disconnect();
}
if (responseCode == 403) {
Log.i(TAG, "responseCode = " + responseCode);
}
HttpURLConnection getRequest = null;
try {
URL serverUrl1 = new URL("https://api.fianitlombard.ru/mobile/checksession?version=1.0.8");
URI uri = URI.create("https://api.fianitlombard.ru/mobile/checksession?version=1.0.8");
getRequest = (HttpURLConnection) serverUrl1.openConnection();
getRequest.setReadTimeout(20000 /* milliseconds */);
getRequest.setConnectTimeout(25000 /* milliseconds */);
getRequest.setRequestMethod("GET");
getRequest.setRequestProperty("Content-Type", "application/json; charset=utf-8");
getRequest.setRequestProperty(COOKIE, cookiesHeader.toString());
Log.i(TAG, "Cookie = " + cookiesHeader.toString());
getRequest.connect();
int responceGetCode = getRequest.getResponseCode();
String responceGetInfo = getRequest.getResponseMessage();
Log.i(TAG, "responceGetCode = " + responceGetCode);
Log.i(TAG, "responceGetInfo = " + responceGetInfo);
if (responceGetCode == 200) {
//Все хорошо
}
if (responceGetCode == 400) {
// Устарела версия, нужно обновление
}
if (responceGetCode == 403) {
//Проблемы с авторизацией
} else {
//Что то другое.
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (getRequest != null)
getRequest.disconnect();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if (postRequest != null) {
postRequest.disconnect();
}
Log.i(TAG, "httpRequest end");
}
catch (InterruptedException | JSONException e) {
e.printStackTrace();
}
return store_id;
}

change below line
getRequest.setRequestProperty(COOKIE, cookiesHeader.toString());
to
getRequest.setRequestProperty( COOKIE, cookiesHeader.get( 0 ) );
toString() method of List will return the hashCode() but not the actual values of List

try to use the following method to get the cookie :
String getHeaderField("Set-Cookie")
you set the cookie by using the lists toString method, which will not give you the current cookie representation, but instead a string matching "[var1, var2, var3]"

The server sends the following in its response header to set a cookie field.
Set-Cookie:name=value
If there is a cookie set, then the browser sends the following in its request header.
Cookie:name=value
See the HTTP Cookie article at Wikipedia for more information.

Related

I want to download a file from the frontend, need to send input stream to the frontend. Using download link to download file from backend

The code below uses a protected url ,username password to get the files to download. I can only manage to download the file in the springboot folder. I want to send the file data to the frontend to have it download there to your downloads.
I might be wrong but I need to send the inputstream to the frontend, then download that data to a file? Any suggestions as to what I am doing wrong when trying to send this data to the frontend.
#RequestMapping(value = "/checkIfProtectedOrPublic/", method = RequestMethod.POST)
public ResponseEntity checkIfProtectedOrPublic(#RequestPart("prm_main") #Valid CheckProtectedData checkProtectedData) throws IOException {
List<PrmMain> prmMainList = prmMainRepository.findAllByCode("PROTECTED_LOGIN");
boolean success = true;
InputStream in = null;
FileOutputStream out = null;
for (int i = 0; i < prmMainList.size(); i++) {
if (prmMainList.get(i).getData().get("email").equals(checkProtectedData.getEmail())) {
String username= (String) prmMainList.get(i).getData().get("email");
String password= (String) prmMainList.get(i).getData().get("password");
try{
URL myUrl = new URL(checkProtectedData.getDownloadLink());
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(30000);
conn.setConnectTimeout(30000);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestMethod("GET");
String userCredentials = username.trim() + ":" + password.trim();
String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
in = conn.getInputStream();
out = new FileOutputStream(checkProtectedData.getFileName());
int c;
byte[] b = new byte[1024];
while ((c = in.read(b)) != -1){
out.write(b, 0, c);
}
}
catch (Exception ex) {
success = false;
}
finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
}
if (out != null)
try {
out.close();
} catch (IOException e) {
}
}
}
}
return ResponseEntity.of(null);
}
//Complete redo of the code
PrmMain loginParameter = prmMainRepository.findAllByCode("PROTECTED_LOGIN").get(0);
if (loginParameter == null)
throw new IllegalArgumentException("Protected Login Not Configured");
// now try and download the file to a byte array using commons - this bypasses CORS requirements
HttpGet request = new HttpGet(checkProtectedData.getDownloadLink());
String login = String.valueOf(loginParameter.getData().get("email"));
String password = String.valueOf(loginParameter.getData().get("password"));
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(login, password));
try
(
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
CloseableHttpResponse response = httpClient.execute(request)
)
{
// if there was a failure send it
if (response.getStatusLine().getStatusCode() != HttpStatus.OK.value())
return new ResponseEntity<>(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
// send back the contents
HttpEntity entity = response.getEntity();
if (entity != null)
{
// return it as a String
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.parseMediaType(entity.getContentType().getValue()));
header.setContentLength(entity.getContentLength());
header.set("Content-Disposition", "attachment; filename=" + checkProtectedData.getFileName());
return new ResponseEntity<>(EntityUtils.toByteArray(entity), header, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
FRONTEND
export async function DownloadFile(url, request) {
axios({
url: `${localUrl + url}`, //your url
method: 'POST',
data: request,
responseType: 'blob', // important
}).then((response) =>
{
fileSaver.saveAs(new Blob([response.data]), request.fileName);
return true;
}).catch(function (error)
{
console.error('Failed ', error);
console.error('Failed ', error); console.log('Failed ', error);
}
);
}

Java Jersey-client header issue

i'm trying to add the following headers to a rest Post call... it works in plain Java but i'm trying to re-write it using the Jersey client library... When I make the post with Jersey I get an error code which isn't listed in the API documentation so i know it must just be a small issue like a missing header... Any idea what i'm doing wrong in the bottom function?
Plain Java add headers function that works:
private void SetDefaultHeaders(HttpURLConnection conn) {
setRequestProperty(conn, "Accept", "*");
setRequestProperty(conn, "Content-Type", "application/x-www-form-urlencoded");
}
Jersey code:
public void logIn(String email, String password) {
if (email != "" && email != null && password != "" && password != null) {
try {
StringBuilder sb = new StringBuilder();
sb.append(Settings.WIFIPLUG_URL);
sb.append("/user_login");
MultivaluedMap<String, String> body = new MultivaluedMapImpl();
body.add("username=", email);
body.add("password=", password);
System.out.println("login url: " + sb.toString());
WebResource webResource = Client.create(new DefaultClientConfig()).resource(sb.toString());
WebResource.Builder builder = webResource.accept("*");
builder.type("application/x-www-form-urlencoded");
ClientResponse response = builder.post(ClientResponse.class, body);
if (response.getStatus() != 200) {
throw new RuntimeException("failed: http error code " + response.getStatus());
}
System.out.println("Response from server: " + response.getEntity(String.class));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Full vanilla java login function:
public String postUserLogin(String username, String password) {
String result = "";
// URL for API to login
String url = "https://wifiplugapi.co.uk:3081/zcloud/api/user_login";
String requestParams = "username=" + username + "&password=" + password;
try {
URL obj = new URL(url);
System.out.println("login url: " + obj);
// Opens the connection
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// Send POST request
con.setDoOutput(true);
con.setDoInput(true);
// Request Headers
con.setRequestMethod("POST");
// Sets all the headers
SetDefaultHeaders(con);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
wr.write(requestParams);// adds values to the request
wr.flush();
wr.close();
// Handles the response
StringBuilder sb = new StringBuilder();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
// if the request was successful OK = 200
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
// Returns Token
} else {
// If the request was bad, reason will be printed
result = "Error, login request failed";
throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
}
result = sb.toString();
// JSON Parser
JsonParser parser = new JsonParser();
JsonObject resultObj = parser.parse(result).getAsJsonObject();
con.disconnect();
if (resultObj.get("token") != null) {
result = (resultObj.get("token")).toString();
System.out.println("JSONObject Result (token): " + result);
} else {
System.out.println("result = " + result);
}
} catch (Exception e) {
e.printStackTrace();
}
// returns token value in string ie. fdg573gb3789gv923378gy83g3
result = result.replaceAll("\"", "");
return result;
}
You shouldn't have the = in the key when doing body.add. It will be added for you
MultivaluedMap<String, String> body = new MultivaluedMapImpl();
body.add("username=", email); // remove the =
body.add("password=", password); // remove the =

Android - Send XML file to PHP API server using HttpURLConnection

So currently, I'm trying to import some data in the form of an XML file to a server. I have successfully logged in and am doing everything through the API of the server. The website/server responds in XML, not sure if that is relevant.
When I use the import data action of the API, the request method is actually a GET and not a POST and the response content-type is text/xml. I want to strictly stick to using HttpURLConnection and I understand that sending this XML file will require some multipart content-type thing but I'm not really sure how to proceed from here.
I've looked at these two examples but it does not work for my application (at least not directly). In addition, I don't really understand where they got some of the request headers from.
Send .txt file, document file to the server in android
http://alt236.blogspot.ca/2012/03/java-multipart-upload-code-android.html
A message from one of the developers have said "To upload the data use the action=importData&gwID=nnnn and with the usual
Multipart content encoding and place the files in the request body as usual."
How would I send my XML file to my server through its API?
This is how you do it:
public void postToUrl(String payload, String address, String subAddress) throws Exception
{
try
{
URL url = new URL(address);
URLConnection uc = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) uc;
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "text/xml");
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.write(payload);
pw.close();
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
bis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
This is my implementation of a Multipart form data upload using HttpURLConnection.
public class WebConnector {
String boundary = "-------------" + System.currentTimeMillis();
private static final String LINE_FEED = "\r\n";
private static final String TWO_HYPHENS = "--";
private StringBuilder url;
private String protocol;
private HashMap<String, String> params;
private JSONObject postData;
private List<String> fileList;
private int count = 0;
private DataOutputStream dos;
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
createServiceUrl();
}
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData, List<String> fileList) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
this.fileList = fileList;
createServiceUrl();
}
public String connectToMULTIPART_POST_service(String postName) {
System.out.println(">>>>>>>>>url : " + url);
StringBuilder stringBuilder = new StringBuilder();
String strResponse = "";
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url.toString()).openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Authorization", "Bearer " + Config.getConfigInstance().getAccessToken());
urlConnection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setChunkedStreamingMode(1024);
urlConnection.setRequestMethod("POST");
dos = new DataOutputStream(urlConnection.getOutputStream());
Iterator<String> keys = postData.keys();
while (keys.hasNext()) {
try {
String id = String.valueOf(keys.next());
addFormField(id, "" + postData.get(id));
System.out.println(id + " : " + postData.get(id));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fileList != null && fileList.size() > 0 && !fileList.isEmpty()) {
for (int i = 0; i < fileList.size(); i++) {
File file = new File(fileList.get(i));
if (file != null) ;
addFilePart("photos[" + i + "][image]", file);
}
}
// forming th java.net.URL object
build();
urlConnection.connect();
int statusCode = 0;
try {
urlConnection.connect();
statusCode = urlConnection.getResponseCode();
} catch (EOFException e1) {
if (count < 5) {
urlConnection.disconnect();
count++;
String temp = connectToMULTIPART_POST_service(postName);
if (temp != null && !temp.equals("")) {
return temp;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 200 represents HTTP OK
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
} else {
System.out.println(urlConnection.getResponseMessage());
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream)
inputStream.close();
} catch (IOException e) {
}
}
return strResponse;
}
public void addFormField(String fieldName, String value) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"" + LINE_FEED + LINE_FEED/*+ value + LINE_FEED*/);
/*dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_FEED);*/
dos.writeBytes(value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void addFilePart(String fieldName, File uploadFile) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + uploadFile.getName() + "\"" + LINE_FEED);
dos.writeBytes(LINE_FEED);
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
dos.writeBytes(LINE_FEED);
dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_FEED);
/* close streams */
fStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addHeaderField(String name, String value) {
try {
dos.writeBytes(name + ": " + value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build() {
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine);
}
/* Close Stream */
if (null != in) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private void createServiceUrl() {
if (null == params) {
return;
}
final Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
boolean isParam = false;
while (it.hasNext()) {
final Map.Entry<String, String> mapEnt = (Map.Entry<String, String>) it.next();
url.append(mapEnt.getKey());
url.append("=");
try {
url.append(URLEncoder.encode(mapEnt.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
url.append(WSConstants.AMPERSAND);
isParam = true;
}
if (isParam) {
url.deleteCharAt(url.length() - 1);
}
}
}

Android file upload to server (written in PHP) not working

I am new to PHP. I am building an android project which needs to upload images to my server. The problem i am having is that when I send just a key and a value (no file) to the server, it works perfectly fine. However, as soon as I try to send a file, the superglobals $_POST and $_FILES in php are empty! The file sent is very small, so its not go to do with the file_max_upload_size. The file is not corrupted. I think it is something to do with the encoding of of the InputStream sent by the app on the android emulator. My code is below:
Java code in the app that sends the image along with a key-value pair:
public Future<JSONObject> asyncSendPOSTRequest(String URL, Map<String, String> params, Map<String, Pair<String,InputStream>> files) throws InterruptedException, ExecutionException, JSONException, UnsupportedEncodingException {
HttpPost request = new HttpPost(URL);
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
if(params!=null) {
for(String key : params.keySet()) {
multipartEntity.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN);
}
}
if(files!=null) {
for(String key : files.keySet()) {
multipartEntity.addPart(key, new InputStreamBody(files.get(key).second,ContentType.MULTIPART_FORM_DATA, files.get(key).first));
}
}
request.setEntity(multipartEntity.build());
Future<JSONObject> future = threadPool.submit(new executeRequest(request));
return future;
}
//Thread to communicate with server.
private class executeRequest implements Callable<JSONObject> {
HttpRequestBase request;
public executeRequest(HttpRequestBase request) {
this.request = request;
}
#Override
public JSONObject call() throws Exception {
HttpResponse httpResponse = httpClient.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder stringReply = new StringBuilder();
String replyLine;
while ((replyLine = reader.readLine()) != null) {
stringReply.append(replyLine);
}
return new JSONObject(stringReply.toString());
}
}
The code on the server:
#!/usr/bin/php
<?php
$uploads_dir = __DIR__ . '/uploads';
$status = -1;
if ($_FILES["picture"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["picture"]["tmp_name"];
$name = $_FILES["picture"]["name"];
$status = move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
$response["status"] = $status;
$response["user_id"] = $_POST["user_id"];
$response["name"] = $name;
$response["extension"] = end (explode(".", $name));
echo json_encode($response);
?>
The possible problem that you set wrong datatype
enctype="multipart/form-data"
public class Helpher extends AsyncTask<String, Void, String> {
Context context;
JSONObject json;
ProgressDialog dialog;
int serverResponseCode = 0;
DataOutputStream dos = null;
FileInputStream fis = null;
BufferedReader br = null;
public Helpher(Context context) {
this.context = context;
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
}
#Override
protected String doInBackground(String... arg0) {
try {
File f = new File(arg0[0]);
URL url = new URL("http://localhost:8888/imageupload.php");
int bytesRead;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
+ f.getName() + "\"";
String contentType = "Content-Type: application/octet-stream";
dos = new DataOutputStream(conn.getOutputStream());
fis = new FileInputStream(f);
dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
dos.writeBytes("Content-Disposition: form-data; name=\"parameterKey\""
+ NEW_LINE);
dos.writeBytes(NEW_LINE);
dos.writeBytes("parameterValue" + NEW_LINE);
dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
dos.writeBytes(contentDisposition + NEW_LINE);
dos.writeBytes(contentType + NEW_LINE);
dos.writeBytes(NEW_LINE);
byte[] buffer = new byte[MAX_BUFFER_SIZE];
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
dos.writeBytes(NEW_LINE);
dos.writeBytes(SPACER + BOUNDARY + SPACER);
dos.flush();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
Log.w(TAG,
responseCode + " Error: " + conn.getResponseMessage());
return null;
}
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
Log.d(TAG, "Sucessfully uploaded " + f.getName());
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
dos.close();
if (fis != null)
fis.close();
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return String.valueOf(serverResponseCode);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
This is the AsyncTask "Helpher" class used for upload image from Android. To call this class use like syntax below.
new Main2Activity.Helpher(this).execute(fileUri.getPath(),parameterValue);
Here fileUri.getPath() local image location.If you want to see the server response value is avilable in " StringBuilder sb" you can print sb value

Socket TimeOutException-Connection timed out

I am trying to connect with Tomcat Server(IP address-192.168.1.120 which is stored in Config.java(static variable APP_SERVER_URL)) but it is giving me socket timeout exception .
How to resolve it.Please help.
But when I
public class ShareExternalServer {
public String shareRegIdWithAppServer(Map<String, String> paramsMap) {
String result = "";
try {
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL);
} catch (MalformedURLException e) {
Log.e("AppUtil", "URL Connection Error: "
+ Config.APP_SERVER_URL, e);
result = "Invalid URL: " + Config.APP_SERVER_URL;
}
StringBuilder postBody = new StringBuilder();
Iterator<Entry<String, String>> iterator = paramsMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
Log.d("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&",body);
byte[] bytes = body.getBytes();
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
httpCon.setConnectTimeout(20000);
OutputStream out = httpCon.getOutputStream();
out.write(bytes);
out.close();
int status = httpCon.getResponseCode();
Log.d("$$$$$$$$$$$$$$$$$$",String.valueOf(status));
/* if (status == 200) {
result = "RegId shared with Application Server. RegId: "
+ regId;
} else {
result = "Post Failure." + " Status: " + status+regId;
}*/
} finally {
if (httpCon != null) {
((HttpURLConnection) httpCon).disconnect();
}
}
} catch (IOException e) {
result = "Post Failure. Error in sharing with App Server.";
Log.e("AppUtil", "Error in sharing with App Server: " + e);
}
return result;
}
}

Categories

Resources