Пример #1
0
  public void post(FileEntity fileEntity) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(fileEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      //
    }
  }
Пример #2
0
  /**
   * Performs an HTTP Post request to the specified url with the specified parameters.
   *
   * @param url The web address to post the request to
   * @param postParameters The parameters to send via the request
   * @return The result of the request
   * @throws Exception
   */
  public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters)
      throws Exception {
    BufferedReader in = null;
    try {
      HttpClient client = getHttpClient();
      HttpPost request = new HttpPost(url);
      request.getParams().setParameter("http.socket.timeout", new Integer(5000));
      UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, HTTP.UTF_8);
      request.setEntity(formEntity);
      HttpResponse response = client.execute(request);
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      StringBuffer sb = new StringBuffer("");
      String line = "";
      String NL = System.getProperty("line.separator");
      while ((line = in.readLine()) != null) {
        sb.append(line + NL);
      }
      in.close();

      String result = sb.toString();
      //	            Log.d("RESPONSE", result);
      return result;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Пример #3
0
 public void run() {
   HttpPost httpPost =
       new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
   //
   httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
   //
   HttpResponse response = null; // This is acting as keep alive.
   //
   while (isActive()) {
     try {
       Thread.sleep(KEEP_ALIVE_PERIOD);
       httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
       response = null;
       response = httpclient.execute(httpPost);
       int status = response.getStatusLine().getStatusCode();
       if (status != RestStreamHanlder.SUCCESS_200) {
         logger.error(
             "Cant register to the remote client, retrying in:"
                 + (KEEP_ALIVE_PERIOD / 1000)
                 + " seconds.");
         structure = registerAndGetStructure();
       }
     } catch (Exception e) {
       logger.warn(e.getMessage(), e);
     } finally {
       if (response != null) {
         try {
           response.getEntity().getContent().close();
         } catch (Exception e) {
           logger.warn(e.getMessage(), e);
         }
       }
     }
   }
 }
Пример #4
0
  /**
   * XMLRPCClient constructor. Creates new instance based on server URI
   *
   * @param XMLRPC server URI
   */
  public XMLRPCClient(URI uri) {
    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    // WARNING
    // I had to disable "Expect: 100-Continue" header since I had
    // two second delay between sending http POST request and POST body
    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    client = getNewHttpClient();
  }
Пример #5
0
  public byte[] post(String postBody, String contentType) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);

    StringEntity stringEntity = new StringEntity(postBody);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(stringEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

      if (response.getEntity() != null) {
        response.getEntity().writeTo(baos);
      }

      body = baos.toByteArray();

      if (body == null || body.length == 0) {
        throw new IOException("invalid response");
      }

      return body;
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      try {
        baos.close();
      } catch (IOException e) {
      }
    }
  }
Пример #6
0
  /**
   * XMLRPCClient constructor. Creates new instance based on server URI
   *
   * @param XMLRPC server URI
   */
  public XMLRPCClient(URI uri, String httpuser, String httppasswd) {
    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    postMethod.addHeader("charset", "UTF-8");
    // UPDATE THE VERSION NUMBER BEFORE RELEASE! <3 Dan
    postMethod.addHeader("User-Agent", "evodroid/" + Constants.versionNumber);

    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    // username & password not needed
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(httpuser, httppasswd);

    // this gets connections working over https
    if (uri.getScheme() != null) {
      if (uri.getScheme().equals("https")) {
        if (uri.getPort() == -1)
          try {
            client = new ConnectionClient(creds, 443);
          } catch (KeyManagementException e) {
            client = new ConnectionClient(creds);
          } catch (NoSuchAlgorithmException e) {
            client = new ConnectionClient(creds);
          } catch (KeyStoreException e) {
            client = new ConnectionClient(creds);
          } catch (UnrecoverableKeyException e) {
            client = new ConnectionClient(creds);
          }
        else
          try {
            client = new ConnectionClient(creds, uri.getPort());
          } catch (KeyManagementException e) {
            client = new ConnectionClient(creds);
          } catch (NoSuchAlgorithmException e) {
            client = new ConnectionClient(creds);
          } catch (KeyStoreException e) {
            client = new ConnectionClient(creds);
          } catch (UnrecoverableKeyException e) {
            client = new ConnectionClient(creds);
          }
      } else {
        client = new ConnectionClient(creds);
      }
    } else {
      client = new ConnectionClient(creds);
    }

    serializer = Xml.newSerializer();
  }
Пример #7
0
 public static String login(String username, String password, String path) {
   String flag = "";
   String __VIEWSTATE = "dDwtMTg3MTM5OTI5MTs7PiFFuiiYPdGI0LwIUfDnLIEo6sfp";
   String txtSecretCode = "";
   String RadioButtonList1 = "学生";
   String Button1 = "登录";
   String lbLanguage = "";
   String hidPdrs = "";
   String hidsc = "";
   HttpResponse response = null;
   // String mianUrl="http://202.119.160.5/content.aspx";
   // 实例化浏览器对象
   HttpClient httpclient = new DefaultHttpClient();
   httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
   // 建立httppost连接
   HttpPost httppost = new HttpPost(path);
   httppost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
   // 添加post到服务器的内容
   List<NameValuePair> parameters = new ArrayList<NameValuePair>();
   parameters.add(new BasicNameValuePair("__VIEWSTATE", __VIEWSTATE));
   parameters.add(new BasicNameValuePair("TextBox1", username));
   parameters.add(new BasicNameValuePair("TextBox2", password));
   parameters.add(new BasicNameValuePair("TextBox3", txtSecretCode));
   parameters.add(new BasicNameValuePair("RadioButtonList1", RadioButtonList1));
   parameters.add(new BasicNameValuePair("Button1", Button1));
   parameters.add(new BasicNameValuePair("lbLanguage", lbLanguage));
   // parameters.add(new BasicNameValuePair("hidPdrs", hidPdrs));
   // parameters.add(new BasicNameValuePair("hidsc", hidsc));
   // 设置post参数个格式
   try {
     httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
     // 开启post
     response = httpclient.execute(httppost);
     int code = response.getStatusLine().getStatusCode();
     if (code == 302) {
       flag = "chenggong";
     } else if (code == 200) {
       flag = "1";
     }
     httppost.abort();
     return flag;
   } catch (Exception e) {
     e.printStackTrace();
     flag = "2";
     httppost.abort();
     return flag;
   }
 }
  private void sendToServer(@Nonnull final String stackTrace, @Nonnull Date time) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    final HttpPost httpPost = new HttpPost(url);
    httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    final List<NameValuePair> values = new ArrayList<NameValuePair>();
    values.add(new BasicNameValuePair("timestamp", time.toString()));
    values.add(new BasicNameValuePair("stacktrace", stackTrace));

    try {
      httpPost.setEntity(new UrlEncodedFormEntity(values, HTTP.UTF_8));
      httpClient.execute(httpPost);
    } catch (IOException e) {
      // ok, just not connected
    }
  }
Пример #9
0
  /**
   * XMLRPCClient constructor. Creates new instance based on server URI (Code contributed by sgayda2
   * from issue #17, and by erickok from ticket #10)
   *
   * @param XMLRPC server URI
   */
  public XMLRPCClient(URI uri) {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    // WARNING
    // I had to disable "Expect: 100-Continue" header since I had
    // two second delay between sending http POST request and POST body
    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    this.client =
        new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams);
  }
Пример #10
0
  /**
   * 请求数据
   *
   * @param token 用户的token
   * @param tokenSecret 用户的tokenSecret
   * @param url 需要获取的数据url(通过url来确定需要获取的数据)
   * @param params 参数
   * @return
   */
  public HttpResponse signRequest(String token, String tokenSecret, String url, List params) {
    HttpPost post = new HttpPost(url);
    ByteArrayOutputStream bos = null;
    String file = null;
    try {
      // 参数的编码转换为utf-8
      post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

      for (int i = 0; i < params.size(); i++) {
        BasicNameValuePair nameValuePair = (BasicNameValuePair) params.get(i);
        if (nameValuePair.getName().equals("pic")) {
          file = nameValuePair.getValue();
        }
      }

      byte[] data = null;
      bos = new ByteArrayOutputStream(1024 * 50);
      if (!TextUtils.isEmpty(file)) {
        paramToUpload(bos, params);
        // 设置表单类型和分隔符
        post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
        Bitmap bf = BitmapFactory.decodeFile(file);
        imageContentToUpload(bos, bf);
        data = bos.toByteArray();
        ByteArrayEntity formEntity = new ByteArrayEntity(data);
        post.setEntity(formEntity);
      }

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } finally {
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    return signRequest(token, tokenSecret, post);
  }
Пример #11
0
  /**
   * 根据不同的请求类型来初始化httppost
   *
   * @param requestType 请求类型
   * @param nameValuePairs 需要传递的参数
   */
  public void iniRequest(String requestType, JSONObject jsonObject) {
    //		this.handler=handler;
    httpPost.addHeader("Content-Type", "text/json");
    httpPost.addHeader("charset", "UTF-8");

    httpPost.addHeader("Cache-Control", "no-cache");
    HttpParams httpParameters = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);
    httpPost.setParams(httpParameters);
    try {
      httpPost.setURI(new URI(URL + requestType));
      httpPost.setEntity(new StringEntity(jsonObject.toString(), HTTP.UTF_8));
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      Log.v(MainApplication.tag, "URI failed");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      Log.v(MainApplication.tag, "setEntity failed");
    }
  }
Пример #12
0
  @Override
  protected String doInBackground(String... params) {
    String loginStatus = "";

    String url = "";

    try {
      HttpPost httppost = new HttpPost(url);
      httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
      List<NameValuePair> parameters = new ArrayList<NameValuePair>();
      parameters.add(new BasicNameValuePair("msg", CrashHandler.errorContent));
      httppost.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
      client.execute(httppost);
    } catch (Throwable e) {
      Debug.Log(e.toString() + "");
    }

    // 重启
    Utils.restartGame();
    return loginStatus;
  }
  @Override
  protected JSONObject doInBackground(Void... params) {
    JSONObject json = null;

    Log.d(TAG, "requestUri=" + tokenUri);

    HttpPost httpRequest = new HttpPost(tokenUri);

    List<NameValuePair> postparams = new ArrayList<NameValuePair>();
    BasicNameValuePair infoParams;
    if (type.equals("token")) infoParams = new BasicNameValuePair("code", infoType);
    else if (type.equals("refresh")) infoParams = new BasicNameValuePair("refresh_token", infoType);
    else infoParams = new BasicNameValuePair("access_token", infoType);
    //		BasicNameValuePair codeParams = new BasicNameValuePair("code", code);
    //		BasicNameValuePair clientIdParams = new BasicNameValuePair("client_id",
    //				clientId);
    BasicNameValuePair grantTypeParams;
    if (type.equals("token"))
      grantTypeParams = new BasicNameValuePair("grant_type", "authorization_code");
    else if (type.equals("refresh"))
      grantTypeParams = new BasicNameValuePair("grant_type", "refresh_token");
    else grantTypeParams = new BasicNameValuePair("grant_type", "access_token");
    BasicNameValuePair redirectUriParams = null;
    if (type.equals("token"))
      redirectUriParams = new BasicNameValuePair("redirect_uri", redirectUri);
    BasicNameValuePair scopeParams = null;
    if (type.equals("refresh")) scopeParams = new BasicNameValuePair("scope", scope);
    postparams.add(infoParams);
    postparams.add(grantTypeParams);
    if (redirectUriParams != null) postparams.add(redirectUriParams);
    if (scopeParams != null) postparams.add(scopeParams);

    //		for (NameValuePair nvp:postparams) {
    //			Log.d(TAG, "Request param "+nvp.getName()+" = "+nvp.getValue());
    //		}

    /* add the post parameters as the request body */
    try {
      httpRequest.setEntity(new UrlEncodedFormEntity(postparams));
      //			Log.d(TAG, "submitted entity "+httpRequest.getEntity().toString());
    } catch (UnsupportedEncodingException e) {
      //			e.printStackTrace();
    }

    httpRequest.addHeader("Accept", "application/json");
    httpRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");

    HttpClient httpClient =
        HttpUtils.getHttpAuthorizationClient(
            tokenUri, clientId, clientSecret, "plain", httpRequest);
    HttpParams httpParams = httpRequest.getParams();
    httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
    httpRequest.setParams(httpParams);

    try {
      HttpResponse httpResponse = httpClient.execute(httpRequest);

      Log.d(TAG, "Request completed with status=" + httpResponse.getStatusLine().getStatusCode());

      /*
       * obtain the headers from the httpResponse. Content-Type and
       * Location are particularly required
       */
      HashMap<String, String> headerMap = HttpUtils.getHeaders(httpResponse);
      String contentType = headerMap.get("content-type");
      String location = headerMap.get("location");

      /*
       * the status code from the HTTP response is also needed in
       * processing
       */
      int statusCode = httpResponse.getStatusLine().getStatusCode();

      Log.d(
          TAG,
          "status="
              + statusCode
              + " CT="
              + contentType
              + " Loc="
              + location
              + " JSON?"
              + HttpUtils.isJSON(contentType)
              + " HTML?"
              + HttpUtils.isHTML(contentType));

      HttpEntity httpEntity = httpResponse.getEntity();
      InputStream is = httpEntity.getContent();

      json = JsonUtils.readJSON(is);
    } catch (java.io.IOException ioe) {
      Log.e(TAG, "IOException " + ioe.getMessage());
      json = new JSONObject();
      try {
        json.put("Exception", "IOException");
        json.put("Message", ioe.getMessage());
      } catch (JSONException e) {
      }
    } catch (JSONException je) {
      Log.e(TAG, "JSONException " + je.getMessage());
      json = new JSONObject();
      try {
        json.put("Exception", "JSONException");
        json.put("Message", je.getMessage());
      } catch (JSONException e) {
      }
    }

    return json;
  }
Пример #14
0
  public DataField[] registerAndGetStructure() throws IOException, ClassNotFoundException {
    // Create the POST request
    HttpPost httpPost =
        new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
    // Add the POST parameters
    httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
    //
    httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
    // Create local execution context
    HttpContext localContext = new BasicHttpContext();
    //
    NotificationRegistry.getInstance().addNotification(uid, this);
    int tries = 0;
    AuthState authState = null;
    //
    while (tries < 2) {
      tries++;
      HttpResponse response = null;
      try {
        // Execute the POST request
        response = httpclient.execute(httpPost, localContext);
        //
        int sc = response.getStatusLine().getStatusCode();
        //
        if (sc == HttpStatus.SC_OK) {
          logger.debug(
              new StringBuilder()
                  .append("Wants to consume the structure packet from ")
                  .append(initParams.getRemoteContactPoint())
                  .toString());
          structure = (DataField[]) XSTREAM.fromXML(response.getEntity().getContent());
          logger.debug("Connection established for: " + initParams.getRemoteContactPoint());
          break;
        } else {
          if (sc == HttpStatus.SC_UNAUTHORIZED)
            authState =
                (AuthState)
                    localContext.getAttribute(
                        ClientContext.TARGET_AUTH_STATE); // Target host authentication required
          else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            authState =
                (AuthState)
                    localContext.getAttribute(
                        ClientContext.PROXY_AUTH_STATE); // Proxy authentication required
          else {
            logger.error(
                new StringBuilder()
                    .append("Unexpected POST status code returned: ")
                    .append(sc)
                    .append("\nreason: ")
                    .append(response.getStatusLine().getReasonPhrase())
                    .toString());
          }
          if (authState != null) {
            if (initParams.getUsername() == null
                || (tries > 1 && initParams.getUsername() != null)) {
              logger.error(
                  "A valid username/password required to connect to the remote host: "
                      + initParams.getRemoteContactPoint());
            } else {

              AuthScope authScope = authState.getAuthScope();
              logger.warn(
                  new StringBuilder()
                      .append("Setting Credentials for host: ")
                      .append(authScope.getHost())
                      .append(":")
                      .append(authScope.getPort())
                      .toString());
              Credentials creds =
                  new UsernamePasswordCredentials(
                      initParams.getUsername(), initParams.getPassword());
              httpclient.getCredentialsProvider().setCredentials(authScope, creds);
            }
          }
        }
      } catch (RuntimeException ex) {
        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        logger.warn("Aborting the HTTP POST request.");
        httpPost.abort();
        throw ex;
      } finally {
        if (response != null && response.getEntity() != null) {
          response.getEntity().consumeContent();
        }
      }
    }

    if (structure == null) throw new RuntimeException("Cannot connect to the remote host.");

    return structure;
  }
Пример #15
0
  /*
   * 获取学生成绩页面的方法
   * parame1 用户名
   * parame2 用户密码
   * parame3 登录界面url
   * parame4 课表查询url
   */
  public static String xskb(
      String username, String password, String path, String mainUrl, String login_kbcx) {
    // 第一次模拟登录用到的固定参数
    String sessionId = null;
    String __VIEWSTATE = "dDwtMTg3MTM5OTI5MTs7PiFFuiiYPdGI0LwIUfDnLIEo6sfp";
    String txtSecretCode = "";
    String RadioButtonList1 = "学生";
    String Button1 = "登录";
    String lbLanguage = "";
    String hidPdrs = "";
    String hidsc = "";
    // 实例化浏览器对象
    HttpClient httpclient = new DefaultHttpClient();

    // 建立httppost连接
    HttpPost httppost = new HttpPost(path);
    httppost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    // 添加post到服务器的内容
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("__VIEWSTATE", __VIEWSTATE));
    parameters.add(new BasicNameValuePair("TextBox1", username));
    parameters.add(new BasicNameValuePair("TextBox2", password));
    parameters.add(new BasicNameValuePair("TextBox3", txtSecretCode));
    parameters.add(new BasicNameValuePair("RadioButtonList1", RadioButtonList1));
    parameters.add(new BasicNameValuePair("Button1", Button1));
    parameters.add(new BasicNameValuePair("lbLanguage", lbLanguage));
    // parameters.add(new BasicNameValuePair("hidPdrs", hidPdrs));
    // parameters.add(new BasicNameValuePair("hidsc", hidsc));
    // 设置post参数个格式
    try {
      httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
      // 开启post
      httpclient.execute(httppost);
      List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
      for (int i = 0; i < cookies.size(); i++) {
        sessionId = "ASP.NET_SessionId=" + cookies.get(i).getValue();
        httppost.abort();
      }
      HttpGet get = new HttpGet(login_kbcx);
      // 此处的refer与之前第一次get的mainurl一致
      get.setHeader("Referer", mainUrl);
      get.addHeader("Cookie", sessionId);
      try {
        HttpResponse httpResponse = new DefaultHttpClient().execute(get);
        HttpEntity entity = httpResponse.getEntity();
        String kbcxhtml = EntityUtils.toString(entity);
        // String Viewstate=JxHtml.getVIEWSTATE(cjcxhtml);

        get.abort();
        return kbcxhtml;

      } catch (Exception e) {
        e.printStackTrace();
        System.out.println(1);
        get.abort();
        return null;
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println(2);
      return null;
    }
  }
Пример #16
0
  public void postData(int action, String url) throws JSONException {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    JSONObject j = new JSONObject();

    try {
      switch (action) {
        case POST_READ:
          j.put("Command", "Read");
          j.put("Dept", depts);
          Log.i(TAG, "DEPTS: " + depts);
          break;
      }

      JSONArray array = new JSONArray();
      array.put(j);

      // Post the data:
      httppost.setHeader("json", j.toString());
      httppost.getParams().setParameter("jsonpost", array);

      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);

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

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF8"));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
          while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
          }
        } catch (IOException e) {
          Log.e(TAG, e.toString());
          e.printStackTrace();
        } finally {
          try {
            is.close();
          } catch (IOException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
          }
        }
        responseString = sb.toString();
        Log.i(TAG, "Response: " + responseString);
      }
      JSONTokener tokener = new JSONTokener(responseString);
      Object o;
      while (tokener.more()) {
        o = tokener.nextValue();
        if (o instanceof JSONArray) {
          JSONArray result = (JSONArray) o;
          parseJSON(result);
        } else {
          // tv.setText("Cannot parse response from server; not a JSON Object");
        }
      }
      // tv.setText(reply);

    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      Log.e(TAG, "Client Protocol Exception:");
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      Log.e(TAG, "IO Exception:");
      e.printStackTrace();
    }
  }
Пример #17
0
  @SuppressWarnings("unchecked")
  @Override
  protected void onHandleIntent(Intent intent) {
    action = (Actions) intent.getSerializableExtra("action");
    actions = (ArrayList<Actions>) intent.getSerializableExtra("actions");
    dbHandler = new DatabaseHandler(getApplicationContext());
    String actionJson;
    if (actions != null) {
      actionJson = Actions.generateActionJson(actions);
    } else {
      actionJson = Actions.generateActionJson(action);
    }

    if (StaticFunctions.hasInternet(getApplicationContext())) {
      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost("http://collegewires.com/wiresapp/send_action.php");
      httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

      try {
        httpPost.setHeader("json", actionJson);
        httpPost.getParams().setParameter("jsonpost", actionJson);
        HttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode()
            == 200) { // means successful in posting json to web
          Log.d("Action Json", "Action JSON to Web");
          // we should now update Synced column of taskActions table to 1
          if (action != null) {
            dbHandler.updateActionColumn(action.getUniqueId(), Actions.ACTION_SYNCED, 1);
          } else {
            for (Actions action : actions) {
              dbHandler.updateActionColumn(action.getUniqueId(), Actions.ACTION_SYNCED, 1);
            }
          }
        } else {
          Log.d("Action Json", response.getStatusLine().toString()); // reason for failure
          // we should now update Synced column of taskActions table to 0
          if (action != null) {
            dbHandler.updateActionColumn(action.getUniqueId(), Actions.ACTION_SYNCED, 0);
          } else {
            for (Actions action : actions) {
              dbHandler.updateActionColumn(action.getUniqueId(), Actions.ACTION_SYNCED, 0);
            }
          }
        }
      } catch (ClientProtocolException e) {
        Log.d("Action Json", "Client Protocol Exception");
      } catch (IOException e) {
        Log.d("Action Json", "IO Exception");
      }
    } else {
      Log.d("Action Json", "data sending failed");
      // we should now update Synced column of taskActions table to 0
      if (action != null) {
        dbHandler.updateActionColumn(action.getUniqueId(), Actions.ACTION_SYNCED, 0);
      } else {
        for (Actions action : actions) {
          dbHandler.updateActionColumn(action.getUniqueId(), Actions.ACTION_SYNCED, 0);
        }
      }
    }
  }
Пример #18
0
  /**
   * Send a payload message.
   *
   * @param payload
   * @throws IOException
   */
  public void send(Payload payload) throws IOException {
    String slackUrl = getURL();

    payload.setUnfurlLinks(true);
    if (StringUtils.isEmpty(payload.getUsername())) {
      payload.setUsername(Constants.NAME);
    }

    String defaultChannel =
        runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_CHANNEL, null);
    if (!StringUtils.isEmpty(defaultChannel) && StringUtils.isEmpty(payload.getChannel())) {
      // specify the default channel
      if (defaultChannel.charAt(0) != '#' && defaultChannel.charAt(0) != '@') {
        defaultChannel = "#" + defaultChannel;
      }
      // channels must be lowercase
      payload.setChannel(defaultChannel.toLowerCase());
    }

    String defaultEmoji =
        runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_EMOJI, null);
    if (!StringUtils.isEmpty(defaultEmoji)) {
      if (StringUtils.isEmpty(payload.getIconEmoji())
          && StringUtils.isEmpty(payload.getIconUrl())) {
        // specify the default emoji
        payload.setIconEmoji(defaultEmoji);
      }
    }

    Gson gson = new GsonBuilder().create();
    String json = gson.toJson(payload);
    log.debug(json);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(slackUrl);
    post.getParams()
        .setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion());
    post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 5000);
    client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 5000);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>(1);
    nvps.add(new BasicNameValuePair("payload", json));

    post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

    HttpResponse response = client.execute(post);

    int rc = response.getStatusLine().getStatusCode();

    if (HttpStatus.SC_OK == rc) {
      // replace this with post.closeConnection() after JGit updates to HttpClient 4.2
      post.abort();
    } else {
      String result = null;
      InputStream is = response.getEntity().getContent();
      try {
        byte[] buffer = new byte[8192];
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len = 0;
        while ((len = is.read(buffer)) > -1) {
          os.write(buffer, 0, len);
        }
        result = os.toString("UTF-8");
      } finally {
        if (is != null) {
          is.close();
        }
      }

      log.error("Slack plugin sent:");
      log.error(json);
      log.error("Slack returned:");
      log.error(result);

      throw new IOException(String.format("Slack Error (%s): %s", rc, result));
    }
  }
    @Override
    protected Void doInBackground(Void... strings) {

      try {
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost(authenticationUrl);
        // added
        httpClient
            .getParams()
            .setParameter(
                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); // Default to HTTP 1.0
        httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

        try {
          final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
          parameters.add(new BasicNameValuePair("j_username", uname));
          parameters.add(new BasicNameValuePair("j_password", pass));
          parameters.add(new BasicNameValuePair("_spring_security_remember_me", "true"));

          System.out.println("Parameters === " + parameters);

          httpPost.setEntity(new UrlEncodedFormEntity(parameters));

          // Create a local instance of cookie store
          CookieStore cookieStore = new BasicCookieStore();

          // Create local HTTP context
          HttpContext localContext = new BasicHttpContext();
          // Bind custom cookie store to the local context
          localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

          // added
          httpPost
              .getParams()
              .setParameter(
                  CoreProtocolPNames.PROTOCOL_VERSION,
                  HttpVersion.HTTP_1_1); // Use HTTP 1.1 for this request only
          httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

          response = httpClient.execute(httpPost, localContext);
          HttpEntity entity = response.getEntity();
          System.out.println("----------------------------------------");
          System.out.println(response.getStatusLine());

          CustomApp appState = ((CustomApp) getApplicationContext());
          List<Cookie> cookies = cookieStore.getCookies();

          cookieName = cookies.get(0).getName();
          cookieValue = cookies.get(0).getValue();
          cookieVersion = cookies.get(0).getVersion();
          cookieDomain = cookies.get(0).getDomain();
          cookiePath = cookies.get(0).getPath();
          cookieExpiry = null;

          for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
          }
          // EntityUtils.consume(entity);

          Log.i("PlaceBooks", "Status Code: " + response.getStatusLine().getStatusCode());

          for (final Header header : response.getAllHeaders()) {
            Log.i("PlaceBooks", header.getName() + "=" + header.getValue());
          }

          final ByteArrayOutputStream bos = new ByteArrayOutputStream();
          response.getEntity().writeTo(bos);
          Log.i("PlaceBooks", "Content: " + bos.toString());

        } catch (final Exception e) {
          Log.e("PlaceBooks", e.getMessage(), e);
          // Dismiss the Dialog
          loginDialog.dismiss();
        }

      } catch (Exception e) {
        e.printStackTrace();
        loginDialog.dismiss();
      }

      return null;
    }
  private void dealing(List<NameValuePair> nvps) {
    String url = "http://api.t.sina.com.cn/blocks/exists.json";
    // 新建一个POST
    HttpPost post = new HttpPost(url);

    // 将参数加到post中
    try {
      post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // 关闭Expect:100-Continue握手
    // 100-Continue握手需谨慎使用,因为遇到不支持HTTP/1.1协议的服务器或者代理时会引起问题
    post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    // 生成CommonsHttpOAuthConsumer对象
    CommonsHttpOAuthConsumer choc =
        new CommonsHttpOAuthConsumer(Constant.consumerKey, Constant.consumerSecret);
    choc.setTokenWithSecret(Constant.userKey, Constant.userSecret);
    // 对post进行签名
    try {
      choc.sign(post);
    } catch (OAuthMessageSignerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (OAuthExpectationFailedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (OAuthCommunicationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // 发送post用来获得HttpResponse
    HttpClient hc = new DefaultHttpClient();
    HttpResponse rp = null;
    try {
      rp = hc.execute(post);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if (200 == rp.getStatusLine().getStatusCode()) {
      try {
        Log.v("getStatusLine", "OK");
        // 将HttpResponse中的内容读到buffer中
        InputStream is = rp.getEntity().getContent();
        Reader reader = new BufferedReader(new InputStreamReader(is), 4000);
        StringBuilder buffer = new StringBuilder((int) rp.getEntity().getContentLength());
        try {
          char[] tmp = new char[1024];
          int l;
          while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
          }
        } finally {
          reader.close();
        }
        // 将buffer转为json可以支持的String类型
        String string = buffer.toString();
        // 销毁rp
        rp.getEntity().consumeContent();
        // 新建JSONObject来处理其中的数据
        try {
          JSONObject data = new JSONObject(string);
          Log.v("result", data.getString("result"));
          // result结果为true则该用户已被加黑名单,false则该用户未被加黑名单

        } catch (JSONException e) {
          e.printStackTrace();
        }

      } catch (IllegalStateException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Пример #21
0
    @Override
    protected String doInBackground(Void... voidstr) {
      JSONObject jsonObject = new JSONObject();

      try {
        jsonObject.accumulate("firstName", firstName);
        jsonObject.accumulate("lastName", lastName);
        jsonObject.accumulate("phoneNumber", phoneNumber);
        jsonObject.accumulate("address", addr);

        // Add a nested JSONObject (e.g. for header information)
        JSONObject header = new JSONObject();
        header.put("deviceType", "Android"); // Device type
        header.put("deviceVersion", "2.0"); // Device OS version
        header.put("language", "es-es"); // Language of the Android client
        jsonObject.put("header", header);
        // Output the JSON object we're sending to Logcat:

        URL = "http://162.243.114.166/cgi-bin/Database_scripts/Registration_script.py";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);
        System.out.println("printing json object : " + jsonObject);
        String se;
        se = jsonObject.toString();
        System.out.println("printing se : " + se);

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        System.out.println("printing req : " + httpPostRequest.getEntity().getContent().toString());
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        // httpPostRequest.setHeader("Content-length", IntegejsonObjSend.toString().length());
        // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you
        // would like to use gzip compression

        InputStream inp = httpPostRequest.getEntity().getContent();
        String req = convertStreamToString(inp);
        System.out.println("printing entities : " + req);

        System.out.println("printing http request message : message is :" + httpPostRequest);
        HttpResponse response = null;
        try {
          response = (HttpResponse) httpclient.execute(httpPostRequest);
        } catch (Exception ex) {
          System.out.println("printing error :" + ex);
        }
        InputStream is = response.getEntity().getContent();
        String res = convertStreamToString(is);
        System.out.println("printing Response is :" + res);
        System.out.println("printing response code : " + response.getStatusLine().getStatusCode());

        // Get hold of the response entity (-> the data)
        HttpEntity entity = response.getEntity();
        String serverresp = entity.toString();
        System.out.println(
            "printing server response, entity length : " + entity.getContentLength());
        System.out.println("printing server response : " + serverresp);

        if (entity != null) {
          // Read the content stream
          InputStream instream = entity.getContent();
          Header contentEncoding = response.getFirstHeader("Content-Encoding");
          if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
          }
          System.out.println("Debug point : 1.3");
          // convert content stream to a String
          String resultString = convertStreamToString(instream);
          instream.close();
          resultString =
              resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

          // Transform the String into a JSONObject
          JSONObject jsonObjRecv = new JSONObject(resultString);
          // Raw DEBUG output of our received JSON object:
          Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");
          System.out.println("Debug point : 1.4");
          return jsonObjRecv;
        }
        // return serverresp;

        try {
          // Add your data
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
          nameValuePairs.add(new BasicNameValuePair("q", se));
          httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          System.out.println("printing http params: " + httpPostRequest.getParams().toString());
          // Execute HTTP Post Request
          HttpResponse response = httpclient.execute(httpPostRequest);

        } catch (ClientProtocolException e) {
          // TODO Auto-generated catch block
        } catch (IOException e) {
          // TODO Auto-generated catch block
        }
      } catch (Exception e) {
        System.out.println("Debug point : 1.4(a)");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
      }
      return null;
    }
Пример #22
0
  /**
   * Call method with optional parameters
   *
   * @param method name of method to call
   * @param params parameters to pass to method (may be null if method has no parameters)
   * @return deserialized method return value
   * @throws XMLRPCException
   */
  @SuppressWarnings("unchecked")
  private Object callXMLRPC(String method, Object[] params) throws XMLRPCException {
    File tempFile = null;
    try {
      // prepare POST body
      if (method.equals("wp.uploadFile")) {
        // String tempFilePath = Environment.getExternalStorageDirectory() + File.separator +
        // "b2evolution" + File.separator + "b2evo-" + System.currentTimeMillis() + ".xml";
        String tempFileName = "b2evo-" + System.currentTimeMillis();
        tempFile = File.createTempFile(tempFileName, null);

        if (!tempFile.exists() && !tempFile.mkdirs()) {
          throw new XMLRPCException("Path to file could not be created.");
        }

        FileWriter fileWriter = new FileWriter(tempFile);
        serializer.setOutput(fileWriter);

        serializer.startDocument(null, null);
        serializer.startTag(null, TAG_METHOD_CALL);
        // set method name
        serializer.startTag(null, TAG_METHOD_NAME).text(method).endTag(null, TAG_METHOD_NAME);
        if (params != null && params.length != 0) {
          // set method params
          serializer.startTag(null, TAG_PARAMS);
          for (int i = 0; i < params.length; i++) {
            serializer.startTag(null, TAG_PARAM).startTag(null, XMLRPCSerializer.TAG_VALUE);
            XMLRPCSerializer.serialize(serializer, params[i]);
            serializer.endTag(null, XMLRPCSerializer.TAG_VALUE).endTag(null, TAG_PARAM);
          }
          serializer.endTag(null, TAG_PARAMS);
        }
        serializer.endTag(null, TAG_METHOD_CALL);
        serializer.endDocument();

        fileWriter.flush();
        fileWriter.close();

        FileEntity fEntity = new FileEntity(tempFile, "text/xml; charset=\"UTF-8\"");
        fEntity.setContentType("text/xml");
        // fEntity.setChunked(true);
        postMethod.setEntity(fEntity);
      } else {
        StringWriter bodyWriter = new StringWriter();
        serializer.setOutput(bodyWriter);

        serializer.startDocument(null, null);
        serializer.startTag(null, TAG_METHOD_CALL);
        // set method name
        serializer.startTag(null, TAG_METHOD_NAME).text(method).endTag(null, TAG_METHOD_NAME);
        if (params != null && params.length != 0) {
          // set method params
          serializer.startTag(null, TAG_PARAMS);
          for (int i = 0; i < params.length; i++) {
            serializer.startTag(null, TAG_PARAM).startTag(null, XMLRPCSerializer.TAG_VALUE);
            if (method.equals("metaWeblog.editPost") || method.equals("metaWeblog.newPost")) {
              XMLRPCSerializer.serialize(serializer, params[i]);
            } else {
              XMLRPCSerializer.serialize(serializer, params[i]);
            }
            serializer.endTag(null, XMLRPCSerializer.TAG_VALUE).endTag(null, TAG_PARAM);
          }
          serializer.endTag(null, TAG_PARAMS);
        }
        serializer.endTag(null, TAG_METHOD_CALL);
        serializer.endDocument();

        HttpEntity entity = new StringEntity(bodyWriter.toString());
        // Log.i("b2evolution", bodyWriter.toString());
        postMethod.setEntity(entity);
      }

      // set timeout to 40 seconds, does it need to be set for both client and method?
      client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
      client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);
      postMethod.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
      postMethod.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);

      // execute HTTP POST request
      HttpResponse response = client.execute(postMethod);

      Log.i("b2evolution", "response = " + response.getStatusLine());
      // check status code
      int statusCode = response.getStatusLine().getStatusCode();

      deleteTempFile(method, tempFile);

      if (statusCode != HttpStatus.SC_OK) {
        throw new XMLRPCException(
            "HTTP status code: "
                + statusCode
                + " was returned. "
                + response.getStatusLine().getReasonPhrase());
      }

      // setup pull parser
      XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
      HttpEntity entity = response.getEntity();
      InputStream is = entity.getContent();

      // Many b2evolution configs can output junk before the xml response (php warnings for
      // example), this cleans it.
      int bomCheck = -1;
      int stopper = 0;
      while ((bomCheck = is.read()) != -1 && stopper <= 5000) {
        stopper++;
        String snippet = "";
        // 60 == '<' character
        if (bomCheck == 60) {
          for (int i = 0; i < 4; i++) {
            byte[] chunk = new byte[1];
            is.read(chunk);
            snippet += new String(chunk, "UTF-8");
          }
          if (snippet.equals("?xml")) {
            // it's all good, add xml tag back and start parsing
            String start = "<" + snippet;
            List<InputStream> streams =
                Arrays.asList(new ByteArrayInputStream(start.getBytes()), is);
            is = new SequenceInputStream(Collections.enumeration(streams));
            break;
          } else {
            // keep searching...
            List<InputStream> streams =
                Arrays.asList(new ByteArrayInputStream(snippet.getBytes()), is);
            is = new SequenceInputStream(Collections.enumeration(streams));
          }
        }
      }

      pullParser.setInput(is, "UTF-8");

      // lets start pulling...
      pullParser.nextTag();
      pullParser.require(XmlPullParser.START_TAG, null, TAG_METHOD_RESPONSE);

      pullParser.nextTag(); // either TAG_PARAMS (<params>) or TAG_FAULT (<fault>)
      String tag = pullParser.getName();
      if (tag.equals(TAG_PARAMS)) {
        // normal response
        pullParser.nextTag(); // TAG_PARAM (<param>)
        pullParser.require(XmlPullParser.START_TAG, null, TAG_PARAM);
        pullParser.nextTag(); // TAG_VALUE (<value>)
        // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

        // deserialize result
        Object obj = XMLRPCSerializer.deserialize(pullParser);
        entity.consumeContent();
        return obj;
      } else if (tag.equals(TAG_FAULT)) {
        // fault response
        pullParser.nextTag(); // TAG_VALUE (<value>)
        // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

        // deserialize fault result
        Map<String, Object> map = (Map<String, Object>) XMLRPCSerializer.deserialize(pullParser);
        String faultString = (String) map.get(TAG_FAULT_STRING);
        int faultCode = (Integer) map.get(TAG_FAULT_CODE);
        entity.consumeContent();
        throw new XMLRPCFault(faultString, faultCode);
      } else {
        entity.consumeContent();
        throw new XMLRPCException(
            "Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>");
      }
    } catch (XMLRPCException e) {
      // catch & propagate XMLRPCException/XMLRPCFault
      deleteTempFile(method, tempFile);
      throw e;
    } catch (Exception e) {
      // wrap any other Exception(s) around XMLRPCException
      deleteTempFile(method, tempFile);
      throw new XMLRPCException(e);
    }
  }
  @Override
  protected String doInBackground(String... params) {
    // HashMap<String, Object> data= params[0];
    // TODO Auto-generated method stub
    String text = null;
    // Create a new HttpClient and Post Header

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    JSONObject json = new JSONObject();

    try {

      // JSON data:

      // json.put("lat", 1);
      // json.put("long", 2);

      ///  json.put("lat", data.get("lat"));
      // json.put("lon", data.get("lon"));

      for (Map.Entry entry : data.entrySet()) {
        String key = (String) entry.getKey();
        Object value = entry.getValue();
        json.put(key, value);

        Log.d("ME", key + " : " + value.toString());
      }

      JSONArray postjson = new JSONArray();
      postjson.put(json);

      // Post the data:

      httppost.setHeader("json", json.toString());

      httppost.getParams().setParameter("jsonpost", postjson);

      // Execute HTTP Post Request

      // System.out.print(json);

      HttpResponse response = httpclient.execute(httppost);

      // 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();
          }
        }
        text = sb.toString();
      }

      Log.d("SERVER RAW REPLY", text);

      return text;
      // Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();

    } catch (Exception e) {
      // TODO Auto-generated catch block

      e.printStackTrace();
      // WebServiceAdapter.publishResult("CAN NOT CONNECT TO SERVER");
      return null;
    }
    // TODO Auto-generated method stub

  }
Пример #24
0
  /*
   * 获取主界面的HTML代码
   */
  public static String getUrl(String username, String password, String path, String mainurl) {

    String __VIEWSTATE = "dDwtMTg3MTM5OTI5MTs7PiFFuiiYPdGI0LwIUfDnLIEo6sfp";
    String txtSecretCode = "";
    String RadioButtonList1 = "学生";
    String Button1 = "登录";
    String lbLanguage = "";
    String sessionId = "";
    // String mianUrl="http://202.119.160.5/content.aspx";
    // 实例化浏览器对象
    HttpClient httpclient = new DefaultHttpClient();

    // 建立httppost连接
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    HttpPost httppost = new HttpPost(path);
    httppost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    // 添加post到服务器的内容
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("__VIEWSTATE", __VIEWSTATE));
    parameters.add(new BasicNameValuePair("TextBox1", username));
    parameters.add(new BasicNameValuePair("TextBox2", password));
    parameters.add(new BasicNameValuePair("TextBox3", txtSecretCode));
    parameters.add(new BasicNameValuePair("RadioButtonList1", RadioButtonList1));
    parameters.add(new BasicNameValuePair("Button1", Button1));
    parameters.add(new BasicNameValuePair("lbLanguage", lbLanguage));
    // parameters.add(new BasicNameValuePair("hidPdrs", hidPdrs));
    // parameters.add(new BasicNameValuePair("hidsc", hidsc));
    // 设置post参数个格式
    try {
      httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
      // 开启post
      httpclient.execute(httppost);
      List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
      for (int i = 0; i < cookies.size(); i++) {
        sessionId = "ASP.NET_SessionId=" + cookies.get(i).getValue();
        httppost.abort();
      }
      // 获取主界面html
      HttpGet get = new HttpGet(mainurl);
      get.setHeader("Referer", mainurl);
      get.addHeader("Cookie", sessionId);
      try {
        HttpResponse httpResponse = new DefaultHttpClient().execute(get);
        HttpEntity entity = httpResponse.getEntity();
        String mainhtml = EntityUtils.toString(entity);
        System.out.println(mainhtml);
        // 获取主界面源代码
        get.abort();
        return mainhtml;
      } catch (Exception e) {
        e.printStackTrace();
        System.out.println(2);
        httppost.abort();
        get.abort();
        return null;
      }
    } catch (Exception e) {
      System.out.println(3);
      httppost.abort();
      return null;
    }
  }