Example #1
1
    @Override
    protected String doInBackground(String... params) {

      byte[] result = null;
      String str = "";

      HttpClient client = new DefaultHttpClient();
      //            HttpGet request = new
      // HttpGet("https://backfinecar-renatdk.c9.io/api/Cars"+mSettings.getString(APP_PREFERENCES_TOKENID,"tokenId"));
      HttpGet request = new HttpGet("https://backfinecar-renatdk.c9.io/api/Cars");

      HttpResponse response;

      try {
        response = client.execute(request);
        result = EntityUtils.toByteArray(response.getEntity());
        str = new String(result, "UTF-8");
        Log.d("Response of GET request", response.toString());
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      return str;
    }
 public static String postStream(String url, String data) {
   InputStream is = null;
   try {
     DefaultHttpClient httpClient = new DefaultHttpClient();
     HttpPost httpPost = new HttpPost(url);
     httpPost.setEntity(new StringEntity(data));
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-type", "application/json");
     HttpResponse httpResponse = httpClient.execute(httpPost);
     Log.i("Httpresponse:", httpResponse.toString());
     HttpEntity httpEntity = httpResponse.getEntity();
     is = httpEntity.getContent();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (ClientProtocolException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (IOException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   }
   Log.e("is:", is.toString());
   return readStream(is);
 }
 public static String postStream2(String url, String data) {
   InputStream is = null;
   String flag = "";
   try {
     DefaultHttpClient httpClient = new DefaultHttpClient();
     HttpPost httpPost = new HttpPost(url);
     httpPost.setEntity(new StringEntity(data));
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-type", "application/json");
     HttpResponse httpResponse = httpClient.execute(httpPost);
     Log.i("Httpresponse:", httpResponse.toString());
     Log.i("Http Response:", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
     if (String.valueOf(httpResponse.getStatusLine().getStatusCode()).trim().equals("404")) {
       flag = "false";
     } else {
       flag = "true";
     }
     HttpEntity httpEntity = httpResponse.getEntity();
     is = httpEntity.getContent();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (ClientProtocolException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (IOException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   }
   Log.e("is:", is.toString());
   return flag;
 }
Example #4
0
  protected String doInBackground(String... auth) {

    HttpClient client = new DefaultHttpClient();
    try {
      client.getConnectionManager().getSchemeRegistry().register(getMockedScheme());
      HttpGet GET =
          new HttpGet("https://api.pcloud.com/listpublinks?iconformat=id&auth=" + auth[0]);

      Log.v("TAG", "Check if it works !!!");
      Log.v(
          "TAG",
          "Request is: " + "https://api.pcloud.com/listpublinks?iconformat=id&auth=" + auth[0]);
      HttpResponse response = client.execute(GET);
      Log.v("TAG", response.toString());
      BufferedReader rd =
          new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      response_code = response.getStatusLine().getStatusCode();

      String line = "";
      while ((line = rd.readLine()) != null) {
        Log.v("TAG", line);
        response_string = response_string + line;
      }

    } catch (Exception e) {
      Log.v("TAG", "SSL Errror " + e.toString());
    }

    return response_string;
  }
Example #5
0
 // String endpoint="http://20.0.1.179";
 // String p="9097";
 public void getSellerInventoryPricingForPDP(Message message, ReadConfig rc) {
   boolean isWorking = false;
   String url = "/service/ipms/getSellerInventoryPricingForPDP";
   String json =
       "{\"orderedSUPCList\":[\"SDL994240556\"],\"zone\":\"1\",\"responseProtocol\":\"PROTOCOL_JSON\",\"requestProtocol\":\"PROTOCOL_JSON\"}";
   String endpoint = rc.getPropValues("ipmsIP");
   String p = rc.getPropValues("ipmsPort");
   String finalUrl = endpoint + ":" + p + url;
   HttpPost request = new HttpPost(finalUrl);
   StringEntity entity = null;
   try {
     entity = new StringEntity(json);
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   entity.setContentType("application/json");
   request.setEntity(entity);
   HttpResponse response = null;
   HttpClient httpclient = HttpClientBuilder.create().build();
   try {
     response = httpclient.execute(request);
   } catch (IOException e) {
     e.printStackTrace();
   }
   try {
     isWorking = response.toString().contains("200");
   } catch (Exception e) {
     System.out.println("getSellerInventoryPricingForPDP");
   }
   if (!isWorking)
     message
         .getErrorMessageList()
         .add("Error: The IPMS is down now on IP :" + endpoint + " and port " + p);
   else System.out.println("IPMS IS UP");
 }
Example #6
0
    @Override
    protected String doInBackground(String... params) {
      Log.d("check", "doing in back");
      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost("http://84.200.84.218/flint/checkuname.php");
      List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(1);
      nameValuePairList.add(new BasicNameValuePair("uname", suname));
      HttpResponse httpResponse = null;
      try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

      try {
        httpResponse = httpClient.execute(httpPost);
        Log.d("response:", httpResponse.toString());
        // Toast.makeText(getApplicationContext(),httpResponse.toString(),Toast.LENGTH_LONG).show();
      } catch (IOException e) {
        e.printStackTrace();
      }
      String data = null;
      HttpEntity ent = httpResponse.getEntity();
      try {
        data = EntityUtils.toString(ent);
      } catch (IOException e) {
        e.printStackTrace();
      }
      Log.d("check", "doing in back done");
      return data;
    }
Example #7
0
  @RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST)
  public String formSubmit(@ModelAttribute User user, Model model)
      throws MalformedURLException, IOException {
    model.addAttribute("user", user);
    HttpPost post =
        new HttpPost(
            "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/");
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName()));
    nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName()));
    nameValuePairs.add(new BasicNameValuePair("email", user.getEmail()));
    nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
    nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation()));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(post);
    response = httpclient.execute(post);
    System.out.println("Status code is " + response.getStatusLine().getStatusCode());
    System.out.println(response.toString());
    System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++");
    System.out.println(response.getFirstHeader("Location"));
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    EntityUtils.consume(response.getEntity());

    /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html");
    FileWriter fileWriter = new FileWriter(newTextFile);
    fileWriter.write(response.toString());
    fileWriter.close();*/
    return "result";
  }
  @Test
  public void testEmotionAPI() {

    HttpResponse resp =
        EmotionRequestAgent.requestEmotionAPI(
            "http://media.npr.org/assets/img/2014/09/26/istock_000019317556large_sq-b51a29cfc009594c39e76f1641f1c1df4a22fd90-s1400.jpg");
    System.out.println(resp.toString());
  }
  @Override
  public void login() {
    loginsuccessful = false;
    try {
      initialize();

      NULogger.getLogger().info("Trying to log in to FileHoot.com");
      httpPost = new NUHttpPost("http://filehoot.com/");

      List<NameValuePair> formparams = new ArrayList<NameValuePair>();
      formparams.add(new BasicNameValuePair("op", "login"));
      formparams.add(new BasicNameValuePair("redirect", ""));
      formparams.add(new BasicNameValuePair("login", getUsername()));
      formparams.add(new BasicNameValuePair("password", getPassword()));

      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
      httpPost.setEntity(entity);
      httpResponse = httpclient.execute(httpPost, httpContext);
      NULogger.getLogger().info(httpResponse.getStatusLine().toString());
      Header lastHeader = httpResponse.getLastHeader("Location");

      if (httpResponse != null && httpResponse.toString().contains("xfss=")) {
        EntityUtils.consume(httpResponse.getEntity());
        loginsuccessful = true;
        username = getUsername();
        password = getPassword();
        NULogger.getLogger().info("FileHoot.com login successful!");

      } else {
        // Get error message
        responseString = EntityUtils.toString(httpResponse.getEntity());
        // FileUtils.saveInFile("FileHootAccount.html", responseString);
        Document doc = Jsoup.parse(responseString);
        String error = doc.select("div.alert-danger").first().text();

        if ("Incorrect Login or Password".equals(error)) {
          throw new NUInvalidLoginException(getUsername(), HOSTNAME);
        }

        // Generic exception
        throw new Exception("Login error: " + "Login Failed");
      }
    } catch (NUException ex) {
      resetLogin();
      ex.printError();
      accountUIShow().setVisible(true);
    } catch (Exception e) {
      resetLogin();
      NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[] {getClass().getName(), e});
      showWarningMessage(Translation.T().loginerror(), HOSTNAME);
      accountUIShow().setVisible(true);
    }
  }
  @Test(priority = 2)
  public void testCreateOrder() throws Exception {
    CustomerOrderListEntry order = new CustomerOrderListEntry();
    order.setBookingDate(Calendar.getInstance());
    order.setCustomerReference("CREF001");
    order.setOrderNumber("ORD001");

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(baseUri);
    StringEntity entity = new StringEntity(objectMapper().writeValueAsString(order));
    entity.setContentType("application/json");
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    System.out.println("Create order:" + response.toString());
  }
 @Override
 protected String doInBackground(String... strings) {
   Log.i(TAG, "starting doInBackground");
   HttpClient httpClient = new DefaultHttpClient();
   HttpGet httpGet = new HttpGet(nextUrl);
   HttpEntity httpEntity = null;
   HttpResponse httpResponse = null;
   try {
     httpResponse = httpClient.execute(httpGet);
     Log.i(TAG, httpResponse.toString());
   } catch (IOException e) {
     e.printStackTrace();
     Log.i(TAG, e.toString());
   }
   InputStream inputStream = null;
   StatusLine statusLine = httpResponse.getStatusLine();
   if (statusLine.getStatusCode() == 200) {
     httpEntity = httpResponse.getEntity();
     try {
       inputStream = httpEntity.getContent();
     } catch (IOException e) {
       e.printStackTrace();
       Log.i(TAG, e.toString());
     }
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
     try {
       while ((completeResponse = bufferedReader.readLine()) != null) {
         builder = builder + completeResponse;
       }
     } catch (IOException e) {
       e.printStackTrace();
       Log.i(TAG, e.toString());
     }
   } else {
     runOnUiThread(
         new Runnable() {
           @Override
           public void run() {
             Toast.makeText(getApplicationContext(), "Problem in network.", Toast.LENGTH_LONG)
                 .show();
           }
         });
   }
   return builder;
 }
  /**
   * Persist registration to third-party servers.
   *
   * <p>Modify this method to associate the user's GCM registration token with any server-side
   * account maintained by your application.
   *
   * @param token The new token.
   */
  private void sendRegistrationToServer(String token, String api) {
    final String API_URL = DataFetcher.API_URL + "register_gcm";

    try {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost(API_URL);

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

      nameValuePairs.add(new BasicNameValuePair("gcm_token", token));
      nameValuePairs.add(new BasicNameValuePair("api_key", api));
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
      HttpResponse response = httpclient.execute(httppost);

      Log.i("Extra", response.toString());
    } catch (IOException e) {
      Log.d(TAG, "Could not send token to server: " + e.toString());
    }
    Log.v(TAG, "Sent token " + token + " to server");
  }
 @Override
 protected Integer doInBackground(String... params) {
   if (mNetworkUtil.isNetworkAvailable(mContext)) {
     if (params[0].trim().length() > 0 && params[1].trim().length() > 0) {
       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost(AUTHENTICATION_URL);
       try {
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
         nameValuePairs.add(new BasicNameValuePair(TAG_USERNAME, params[0].trim()));
         nameValuePairs.add(new BasicNameValuePair(TAG_PASSWORD, params[1].trim()));
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         HttpResponse response = httpclient.execute(httppost);
         if (response.toString().equals("")) return SUCCESS;
         else return ERROR_WRONG_CREDENTIALS;
       } catch (Exception e) {
         e.printStackTrace();
         return ERROR_EXCEPTION;
       }
     } else return ERROR_WRONG_INPUT;
   } else return ERROR_NO_CONNECTION;
 }
 public void sendFromInputStream(InputStream input, long length) {
   client = new MyHttpClient(context);
   HttpPost httppost = new HttpPost("https://csl.ece.iastate.edu/android/appdata.php");
   httppost.setEntity(new InputStreamEntity(input, length));
   HttpResponse response;
   try {
     response = client.execute(httppost);
     Log.v("mark", "SSLCommunication HttpResponse:" + response.toString());
   } catch (ClientProtocolException e) {
     Log.v(
         "mark",
         "SSLCommunication sendFile ClientProtocolException:"
             + e.getClass()
             + " with "
             + e.getMessage());
   } catch (IOException e) {
     Log.v(
         "mark",
         "SSLCommunication sendFile IOException:" + e.getClass() + " with " + e.getMessage());
   }
 }
Example #15
0
    @Override
    protected String doInBackground(String... params) {
      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost("http://84.200.84.218/flint/signup.php");

      List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(9);

      nameValuePairList.add(new BasicNameValuePair("uname", suname));
      nameValuePairList.add(new BasicNameValuePair("uph", snum));
      nameValuePairList.add(new BasicNameValuePair("gender", gender));
      nameValuePairList.add(new BasicNameValuePair("dob", bday));
      nameValuePairList.add(new BasicNameValuePair("guname", guname));
      nameValuePairList.add(new BasicNameValuePair("gemail", guemail));
      nameValuePairList.add(new BasicNameValuePair("gpic", guserProfilePicUrl));
      nameValuePairList.add(new BasicNameValuePair("fb", fb));
      nameValuePairList.add(new BasicNameValuePair("twitter", twitter));

      HttpResponse httpResponse = null;
      try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

      try {
        httpResponse = httpClient.execute(httpPost);
        Log.d("response:", httpResponse.toString());
        // Toast.makeText(getApplicationContext(),httpResponse.toString(),Toast.LENGTH_LONG).show();
      } catch (IOException e) {
        e.printStackTrace();
      }
      String data = null;
      HttpEntity ent = httpResponse.getEntity();
      try {
        data = EntityUtils.toString(ent);
      } catch (IOException e) {
        e.printStackTrace();
      }
      return data;
    }
  private void handleRequest(RequestObject reqObj) {
    final Path path = reqObj.getPath();
    final HttpServerConnection conn = reqObj.getConn();
    final HttpRequest req = reqObj.getRequest();

    WebServerLog.log(this, "Request handler got a request:\n" + req.toString());

    if (!req.getRequestLine().getMethod().toUpperCase().equals("GET")) {
      return;
    }

    final HttpResponse response =
        new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, ReasonPhrases.OK);

    boolean applyFilters;
    applyFilters = handleFileRequest(path, response);

    if (applyFilters) {
      filterChain.reset(path.toString());
      filterChain.doFilter(reqObj.getRequest(), response);
    }
    try {
      proc.process(response, new BasicHttpContext());
      addContentType(path, response);
    } catch (HttpException | IOException e1) {
      WebServerLog.log(this, "Request handler failed to 'process' response after filtering");
      e1.printStackTrace();
    }
    WebServerLog.log(this, "Request handler is sending a response:\n" + response.toString());

    try {
      conn.sendResponseHeader(response);
      conn.sendResponseEntity(response);
    } catch (HttpException | IOException e) {
      WebServerLog.log(this, "Request handler has encountered error while sending response");
      e.printStackTrace();
    }
  }
    protected Object doInBackground(Object[] objects) {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://mishra14.ddns.net/fetchdata.php");
      try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("username", username));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // httpclient.execute(httppost);
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        Log.e("Error", response.toString());
        HttpEntity entity = response.getEntity();
        if (entity != null) {
          InputStream stream = entity.getContent();
          String data = convertStreamToString(stream);
          readAndParseJSON(data);
          stream.close();
        }
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
      } catch (IOException e) {
        // TODO Auto-generated catch block
      }
      try {
        URL url =
            new URL(
                "http://jitesh.pythonanywhere.com/examples/email_test/sendemail?price=500&company=Apple&change=5");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.v("Checking Exception", "IOException");
      }

      return null;
    }
 /**
  * Requests mobile device for the producer returns the HTTP response code and 0 if failed to
  * execute post.
  *
  * @param c
  * @return
  */
 public int requestProducer(Consumer c) {
   int result = 0;
   APIConnection api = new APIConnection();
   String param = c.consumerToJSON();
   System.out.println(param);
   HttpResponse response = api.post(api.getConsumerRequest(), param);
   // HttpResponse response = api.post(api.getConsumerRequest(), c.consumerToJSON());
   try {
     System.out.println(
         response.toString()); // ///////////////remove just to show response for now
     result = api.getResponse(response);
     if (result == 200) {
       HttpEntity entity = response.getEntity();
       JSONArray jsonArray = getJSONArray(entity);
       if (jsonArray == null) {
         return 0;
       } else {
         // currently takes first response and uses that port/ip
         JSONObject json = jsonArray.getJSONObject(0);
         System.out.println(json.toString());
         String port = (String) json.get(api.getPort_key());
         String ip = (String) json.get(api.getIp_key());
         String device = (String) json.get(api.getDevice_id_key());
         c.setConnection_ip(ip);
         c.setConnection_port(port);
         c.setConnection_device_id(device);
         return result;
       }
     }
   } catch (Exception e) {
     System.out.println("Exception thrown");
     e.printStackTrace();
     return result;
   }
   return result;
 }
    @Override
    protected String doInBackground(String... params) {
      // TODO Auto-generated method stub

      for (String url : params) {
        try {
          ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
          nameValuePairs1.add(new BasicNameValuePair("catid", keyword));
          HttpClient httpclient1 = new DefaultHttpClient();
          HttpPost httppost1 = new HttpPost(url);
          httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
          HttpResponse httpResponse1 = httpclient1.execute(httppost1);
          Log.d("ent", httpResponse1.toString());
          HttpEntity resEntityGet1 = httpResponse1.getEntity();
          if (resEntityGet1 != null) {
            // do something with the response
            response1 = EntityUtils.toString(resEntityGet1);
            Log.i("GET RESPONSE", response1);
            Log.d("response", response1);

            JSONArray arr1 = new JSONArray(response1);
            String arrlen1 = Integer.toString(arr1.length());
            Log.d("Array Length", arrlen1);
            len = Integer.parseInt(arrlen1);
            menu = new String[len];
            veg = new String[len];
            id = new String[len];
            desc = new String[len];
            cost = new String[len];
            size = new String[len];
            res = new String[len];

            b.putInt("length", len);
            for (int i = 0; i < arr1.length(); i++) {
              JSONObject food1 = null;
              food1 = arr1.getJSONObject(i);
              menu[i] = food1.getString("menu_name");
              veg[i] = food1.getString("type");
              id[i] = food1.getString("menu_id");
              desc[i] = food1.getString("menu_desc");
              cost[i] = food1.getString("unit_cost");
              size[i] = food1.getString("size");
              res[i] = food1.getString("res_name");
            } // for
            b.putStringArray("menu", menu);
            b.putStringArray("type", veg);
            b.putStringArray("id", id);
            b.putStringArray("desc", desc);
            b.putStringArray("cost", cost);
            b.putStringArray("size", size);
            b.putStringArray("res", res);

            int l = menu.length;
            int i;
            for (i = 0; i < l; i++) {
              Log.d("c", menu[i]);
            }
          } //

        } catch (Exception e) {
        }
      }
      return response1;
    }
Example #20
0
  /**
   * 上传文件http请求客户端
   *
   * @param url 请求地址
   * @param srcPath 本地文件全路径
   * @param decPath 服务端存储目录
   * @param clusterId 集群id
   * @param owner 所属业务方
   * @return
   */
  static int uploadPost(Path localFile, String decPath, String clusterId, String owner) {
    SessionState ss = SessionState.get();
    Result result = new Result();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    // 传入svn用户名和密码
    credsProvider.setCredentials(
        new AuthScope(
            AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
        new UsernamePasswordCredentials("dw_zouruochen", "*****@*****.**"));
    CloseableHttpClient closeableHttpClient =
        HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    HttpPost httpPost = new HttpPost(UPLOAD_URL);

    try {
      FileBody srcFile = new FileBody(localFile.toFile());
      StringBody dec = new StringBody(decPath, Consts.UTF_8);
      StringBody id = new StringBody(clusterId, Consts.UTF_8);
      StringBody ownerStr = new StringBody(owner, Consts.UTF_8);

      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
      String name = localFile.getFileName().toString();

      reqEntity.addPart("clusterId", id);
      reqEntity.addPart("decPath", dec);
      reqEntity.addPart("srcFile", srcFile);
      reqEntity.addPart("owner", ownerStr);

      StringBody fileName = new StringBody(name, Consts.UTF_8);
      reqEntity.addPart("fileName", fileName);

      httpPost.setEntity(reqEntity);
      HttpResponse response = closeableHttpClient.execute(httpPost);
      int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode == HttpStatus.SC_OK) {
        // System.out.println("上传服务器正常响应.....");
        ss.info.println("上传服务器正常响应.....");
        HttpEntity resEntity = response.getEntity();
        ss.info.println("contentEncoding:" + resEntity.getContentEncoding());
        result.setData(EntityUtils.toString(resEntity));
        result.setCode(0);
        EntityUtils.consume(resEntity);
        ss.info.println(result.toString());
        return result.getCode();
      } else {
        result.setCode(-1);
        result.setMsg("uploadPost error!" + response.toString());
        ss.err.println(result.toString());
        return result.getCode();
      }
    } catch (Exception e) {
      LOG.error("uploadPost error!", e);
      result.setCode(-1);
      result.setMsg("uploadPost error!");
      ss.err.println(result.toString());
      return result.getCode();
    } finally {
      try {
        httpPost.releaseConnection();
      } catch (Exception ignore) {
        LOG.error("uploadPost error!", ignore);
      }
    }
  }
Example #21
0
  @SuppressWarnings("deprecation")
  public static JSONObject deleteVehicleData()
      throws JSONException, IllegalStateException, IOException {

    try {
      @SuppressWarnings("deprecation")
      HttpClient httpclient = new DefaultHttpClient();
      @SuppressWarnings("deprecation")
      // HttpPost httppost = new
      // HttpPost("http://192.168.0.223/ExApis/api/portalEntity");
      HttpPost httppost = new HttpPost(AppConstant.PayBillURL_Local);
      JSONObject jObj_RequestData = new JSONObject();
      JSONObject jsonObject = new JSONObject();

      jsonObject.put("UserID", Storage.getinstance().getString("UserID"));
      jsonObject.put("AuthenticationToken", Storage.getinstance().getString("AuthenticationToken"));
      jsonObject.put("EntityType", AppConstant.DELETE_VEHICLE_ENTITY_TYPE);
      // jsonObject.put("EntityID", companyID);
      jsonObject.put("EntityID", 10048);

      jObj_RequestData.put("RequestData", jsonObject);
      jObj_RequestData.put("Action", "DeletePortalEntity");

      // Post the data:
      try {
        httppost.setEntity(new StringEntity(jObj_RequestData.toString()));
      } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
      }
      httppost.setHeader(HTTP.CONTENT_TYPE, "application/json");

      System.out.print(jObj_RequestData);
      HttpResponse response = null;
      try {
        response = httpclient.execute(httppost);
      } catch (ClientProtocolException e1) {
        e1.printStackTrace();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      Log.e("Response Booking", response.toString());

      // for JSON:
      if (response != null) {
        InputStream is = response.getEntity().getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
          while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
          }
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          try {
            is.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        Log.e("Value", sb.toString());
        String re = convertStandardJSONString1(sb.toString());
        sumbmitResponse = new JSONObject(convertStandardJSONString1(sb.toString()));
        // JSONObject obj = new JSONObject(sb.toString());
        // _status = obj.getString("status");

      }
    } catch (Exception e) {
      Log.e("Exception at activation screen", e + "");
    }
    return sumbmitResponse;
  }
Example #22
0
  @SuppressWarnings("deprecation")
  public static JSONObject postLoginData()
      throws JSONException, IllegalStateException, IOException {
    array = new JSONArray();
    try {
      @SuppressWarnings("deprecation")
      HttpClient httpclient = new DefaultHttpClient();
      @SuppressWarnings("deprecation")
      // HttpPost httppost = new
      // HttpPost("http://192.168.0.223/excellonapi/api/request");
      HttpPost httppost = new HttpPost(AppConstant.PayBillURL_Local);
      JSONObject jObj_RequestData = new JSONObject();
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("UserID", Integer.parseInt(Storage.getinstance().getString("UserID")));
      jsonObject.put("UserName", Storage.getinstance().getString("UserName"));
      jsonObject.put("Password", Storage.getinstance().getString("Password"));
      jsonObject.put("AuthenticationToken", Storage.getinstance().getString("AuthenticationToken"));
      jsonObject.put("EntityType", "");

      jObj_RequestData.put("RequestData", jsonObject);
      jObj_RequestData.put("Action", "Logoff");

      array.put(jObj_RequestData);
      // JSONArray postjson = new JSONArray();
      // postjson.put(json);

      // Post the data:
      try {
        httppost.setEntity(new StringEntity(array.toString()));
      } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
      }
      httppost.setHeader(HTTP.CONTENT_TYPE, "application/json");

      System.out.print(jObj_RequestData);
      HttpResponse response = null;
      try {
        response = httpclient.execute(httppost);
      } catch (ClientProtocolException e1) {
        e1.printStackTrace();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      Log.e("Response", response.toString());

      // for JSON:
      if (response != null) {
        InputStream is = response.getEntity().getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
          while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
          }
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          try {
            is.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        Log.e("Value", sb.toString());
        String re = convertStandardJSONString1(sb.toString());
        sumbmitResponse = new JSONObject(convertStandardJSONString1(sb.toString()));
        // JSONObject obj = new JSONObject(sb.toString());
        // _status = obj.getString("status");

      }

    } catch (Exception e) {
      Log.e("Exception at activation screen", e + "");
    }
    return sumbmitResponse;
  }
 /**
  * Receive an HTTP response.
  *
  * @param invocationId Method invocation identifier.
  * @param response The response instance.
  */
 public void receiveResponse(String invocationId, HttpResponse response) {
   String responseAsString = response == null ? "" : response.toString();
   logger.log(
       Level.INFO,
       String.format("invocationId: %s\r\nrequest: %s", invocationId, responseAsString));
 }
Example #24
0
    @Override
    public void run() {
      Log.d(UPLOAD_SERVICE_TAG, "Thread Started");
      final String serverURL = myPreference.getServerLocation();
      final String userID = myPreference.getUserID();
      final String passKey = myPreference.getPassKey();
      if (userAuthenticated(userID, passKey, serverURL)) {

        db.clearUploadIDs();
        boolean errorExit;
        do {
          errorExit = false;
          int retryCount = 0;
          int code = -1;
          HttpResponse response = null;
          final String locations = db.getLocationsAsXML(uploadTime);
          Log.d(UPLOAD_SERVICE_TAG, locations);
          final AndroidHttpClient http = AndroidHttpClient.newInstance("TrackMe");
          final HttpPost httpPost = new HttpPost(serverURL + "/api/v1/xml/store");
          GzipHelper.setCompressedEntity(UploadService.this, locations, httpPost);
          httpPost.addHeader("userid", userID);
          httpPost.addHeader("passkey", passKey);
          while (retryCount < MAX_RETRY_COUNT) {

            try {
              response = http.execute(httpPost);
              Log.d(UPLOAD_SERVICE_TAG, response.toString());
              code = response.getStatusLine().getStatusCode();
              errorExit = false;
              retryCount = MAX_RETRY_COUNT;
            } catch (final ClientProtocolException e) {
              retryCount += 1;
              errorExit = true;
            } catch (final IOException e) {
              retryCount += 1;
              errorExit = true;
              e.printStackTrace();
            }
          }
          http.close();

          if (code == HttpStatus.SC_OK) {
            final Document doc = ResponseParsing.getDomElement(ResponseParsing.getXML(response));

            final int uploadID = Integer.parseInt(doc.getDocumentElement().getAttribute("uid"));

            final NodeList nl = doc.getElementsByTagName("batch");

            for (int i = 0; i < nl.getLength(); i++) {
              final Element e = (Element) nl.item(i);
              final String sessionID = e.getAttribute("sid");
              final int batchID = Integer.parseInt(e.getAttribute("bid"));

              if (e.getAttribute("accepted").equals("true")) {
                Log.d(UPLOAD_SERVICE_TAG, "Boolean New " + e.getAttribute("accepted"));
                final int uploadedCount =
                    db.moveLocationsToSessionTable(uploadID, sessionID, batchID);
                updatePreferences.addUploadedCount(uploadedCount);
                final Intent intent = new Intent(MainActivity.MAIN_ACTIVITY_UPDATE_DEBUG_UI);
                LocalBroadcastManager.getInstance(UploadService.this).sendBroadcast(intent);
              } else {
                final int archivedCount = db.archiveLocations(uploadID, sessionID, batchID);
                updatePreferences.addArchivedCount(archivedCount);
                final Intent intent = new Intent(MainActivity.MAIN_ACTIVITY_UPDATE_DEBUG_UI);
                LocalBroadcastManager.getInstance(UploadService.this).sendBroadcast(intent);
              }
            }
          } else {
            final String message =
                "Server response:\n" + response.getStatusLine().getReasonPhrase();
            getApplication().startActivity(UserError.makeIntent(getBaseContext(), message));
            errorExit = true;
          }
        } while (db.getQueuedLocationsCount(uploadTime) > 0 && !errorExit);
      }

      synchronized (UploadService.this) {
        running = false;
        stopForeground(true);
      }
      Log.d(UPLOAD_SERVICE_TAG, "Thread Compleated");
    }