예제 #1
0
  public synchronized void updateHtmlEntry(String key, String html) throws HttpException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(catalogDbURL + "update");
    System.err.println(key);
    postMethod.addParameter("key", key);
    postMethod.addParameter("columns", html);
    try {
      httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
      try {
        String resp = postMethod.getResponseBodyAsString();
        System.err.println(resp);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      throw new HttpException("failed to post form.");
    }
  }
예제 #2
0
 public HttpClient getAuthenticatedHttpClient(
     String strLogonURL, String strLogonUserId, String strLogonPassword) {
   HttpClient httpClient = new HttpClient();
   int code = 0;
   if (strLogonURL != null && strLogonUserId != null && strLogonPassword != null) {
     PostMethod postMethod = new PostMethod(strLogonURL);
     postMethod.setParameter("username", strLogonUserId);
     postMethod.setParameter("password", strLogonPassword);
     postMethod.setParameter("login-form-type", "pwd");
     try {
       code = httpClient.executeMethod(postMethod);
       APPLICATION_LOGGER.info("Login Http Status {} ", code);
     } catch (HttpException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     }
   } else {
     APPLICATION_LOGGER.error("invalid logon configurations found");
   }
   if (code != 200) {
     APPLICATION_LOGGER.error("Unable to login to server, Http Status Code = {}", code);
     httpClient = null;
   }
   return httpClient;
 }
예제 #3
0
 public static void main(String[] args) {
   HttpClient client = new HttpClient(); // Create an instance of HttpClient.
   GetMethod method = new GetMethod(url); // Create a method instance.	
   method
       .getParams()
       .setParameter(
           HttpMethodParams.RETRY_HANDLER,
           new DefaultHttpMethodRetryHandler(
               3, false)); // Provide custom retry handler is necessary
   try {
     int statusCode = client.executeMethod(method); // Execute the method.
     if (statusCode != HttpStatus.SC_OK) {
       System.err.println("Method failed: " + method.getStatusLine());
     }
     byte[] responseBody = method.getResponseBody(); // Read the response body.
     System.out.println(
         new String(
             responseBody)); // Deal with the response.// Use caution: ensure correct character
                             // encoding and is not binary data
   } catch (HttpException e) {
     System.err.println("Fatal protocol violation: " + e.getMessage());
     e.printStackTrace();
   } catch (IOException e) {
     System.err.println("Fatal transport error: " + e.getMessage());
     e.printStackTrace();
   } finally {
     method.releaseConnection(); // Release the connection.
   }
 }
  public void testWriteRequestReleaseConnection() {

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);

    client.setHttpConnectionManager(connectionManager);

    GetMethod get =
        new GetMethod("/") {
          protected boolean writeRequestBody(HttpState state, HttpConnection conn)
              throws IOException, HttpException {
            throw new IOException("Oh no!!");
          }
        };

    try {
      client.executeMethod(get);
      fail("An exception should have occurred.");
    } catch (HttpException e) {
      e.printStackTrace();
      fail("HttpException should not have occurred: " + e);
    } catch (IOException e) {
      // expected
    }

    try {
      connectionManager.getConnectionWithTimeout(client.getHostConfiguration(), 1);
    } catch (ConnectTimeoutException e) {
      e.printStackTrace();
      fail("Connection was not released: " + e);
    }
  }
  public void test_getContentsFolder() {

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e1) {

      e1.printStackTrace();
    }

    // Get the content
    HttpMethod get_col_contents =
        new GetMethod(
            SLING_URL + COLLECTION_URL + slug + "/" + CONTENTS_FOLDER + "/" + "sling:resourceType");
    try {
      client.executeMethod(get_col_contents);
    } catch (HttpException e) {

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

      e.printStackTrace();
    }
    // handle response.
    String response_body = "";
    try {
      response_body = get_col_contents.getResponseBodyAsString();
    } catch (IOException e) {

      e.printStackTrace();
    }

    assertEquals(response_body, CONTENTS_RESOURCE_TYPE);
  }
  public void runSimpleLoginLoadTest() {
    HttpClient httpClient = getHttpClient();

    // RequestEntity re = new StringRequestEntity(raw_body, "text/xml",
    // "UTF-16");

    try {

      PostMethod postMethod = new PostMethod(getAsvip() + "mas/login");
      postMethod.addParameters(getReqParams());
      int statuscode = httpClient.executeMethod(postMethod);
      byte[] responseBody = postMethod.getResponseBody();
      postMethod.releaseConnection();
      // System.out.println(statuscode + " LOGIN   RESPONSE  ---- "+ new String(responseBody));

      postMethod = new PostMethod(getAsvip() + "mas/logout");
      statuscode = httpClient.executeMethod(postMethod);
      responseBody = postMethod.getResponseBody();
      //	System.out.println(statuscode + "  LOGOUT  RESPONSE  ---- "+ new String(responseBody));
      postMethod.releaseConnection();

    } catch (HttpException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Send the command to Solr using a GET
   *
   * @param queryString
   * @param url
   * @return
   * @throws IOException
   */
  private static String sendGetCommand(String queryString, String url) throws IOException {
    String results = null;
    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod(url);
    get.setQueryString(queryString.trim());

    client.executeMethod(get);
    try {
      // Execute the method.
      int statusCode = client.executeMethod(get);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + get.getStatusLine());
        results = "Method failed: " + get.getStatusLine();
      }

      results = getStringFromStream(get.getResponseBodyAsStream());
    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      get.releaseConnection();
    }
    return results;
  }
예제 #8
0
  public static Bitmap readImg(String id) {

    String uri = "http://" + PostUrl.Media + ":8080/upload/" + id + ".jpg";
    HttpClient client = new HttpClient();
    client.getParams().setContentCharset("utf-8");
    client.getParams().setSoTimeout(10000);
    client
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    GetMethod getMethod = new GetMethod(uri);
    System.out.println("1");
    try {
      if (client.executeMethod(getMethod) == HttpStatus.SC_OK) {
        System.out.println("2");
        InputStream inputStream = getMethod.getResponseBodyAsStream();
        System.out.println("3");
        Bitmap img = BitmapFactory.decodeStream(inputStream);
        inputStream.close();

        return img;
      }

    } catch (HttpException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    } catch (IOException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    } finally {
      getMethod.releaseConnection();
    }
    System.out.println("图片下载不了");
    return null;
  }
  public TicketsResponse checkTickets(TicketsRequest request) {
    String jsonResp = null;
    TicketsResponse response = null;
    TicketsResponseError responseError = null;
    try {
      jsonResp = sendRequest(request);
      try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        response = mapper.readValue(jsonResp, TicketsResponse.class);
      } catch (JsonMappingException e) {
        //				logger.error("Could not parse JSON, trying to parse an error. Original exception: ",
        // e);
        responseError = new ObjectMapper().readValue(jsonResp, TicketsResponseError.class);
        TicketsResponse invaildResponse = new TicketsResponse();
        invaildResponse.setError(true);
        invaildResponse.setErrorDescription(responseError.getErrorDescription());
        logger.error("UzGovUa error description: " + responseError.getErrorDescription());
        return invaildResponse;
      }
    } catch (HttpException e) {
      e.printStackTrace();
      logger.error(e.getMessage(), e);
    } catch (SocketTimeoutException e) {
      logger.error(e.getMessage(), e);
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
    }

    return response;
  }
예제 #10
0
  public static Boolean urlIsTrue(String id) {
    String uri = "http://" + PostUrl.Media + ":8080/upload/" + id + ".jpg";
    HttpClient client = new HttpClient();
    client.getParams().setContentCharset("utf-8");
    client.getParams().setSoTimeout(10000);
    client
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    GetMethod getMethod = new GetMethod(uri);
    System.out.println("1");
    try {
      if (client.executeMethod(getMethod) == HttpStatus.SC_OK) {
        return true;
      }
    } catch (HttpException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    } catch (IOException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    } finally {
      getMethod.releaseConnection();
    }
    System.out.println("图片下载不了");
    return false;
  }
예제 #11
0
  private static boolean createRepo(
      final String scmUrl, final String password, final String repository) {
    HttpClient client = new HttpClient();
    String uri = scmUrl + API + "/projects";
    LOGGER.debug("Create Repo: {}", uri);
    PostMethod post = new PostMethod(uri);

    post.setParameter("name", repository);
    post.setParameter("private_token", password);
    try {
      int result = client.executeMethod(post);
      LOGGER.info("Return code: " + result);
      for (Header header : post.getResponseHeaders()) {
        LOGGER.info(header.toString().trim());
      }
      LOGGER.info(post.getResponseBodyAsString());
    } catch (HttpException e) {
      e.printStackTrace();
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    } finally {
      post.releaseConnection();
    }
    return true;
  }
  public void test_getTagsFolder() {

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e1) {

      e1.printStackTrace();
    }

    String response_body = "";
    HttpMethod get_col_tags =
        new GetMethod(
            SLING_URL + COLLECTION_URL + slug + "/" + TAGS_FOLDER + "/" + "sling:resourceType");
    try {
      client.executeMethod(get_col_tags);
    } catch (HttpException e) {

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

      e.printStackTrace();
    }

    try {
      response_body = get_col_tags.getResponseBodyAsString();
    } catch (IOException e) {

      e.printStackTrace();
    }

    assertEquals(response_body, TAGS_RESOURCE_TYPE);
    get_col_tags.releaseConnection();
  }
  private String doCall(String uri) throws IOException {
    System.out.println("We're calling the uri");
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    HttpMethod getMethod = new GetMethod(uri);

    try {
      int response = httpClient.executeMethod(getMethod);

      if (response != 200) {
        throw new IOException("HTTP problem, httpcode: " + response);
      }

      InputStream stream = getMethod.getResponseBodyAsStream();
      String responseText = responseToString(stream);
      return responseText;

    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
예제 #14
0
  protected void loadNetImage() {
    String url = "http://ww2.sinaimg.cn/thumbnail/675e5a2bjw1e0pydwgwgnj.jpg";
    HttpClient httpClient = null;
    GetMethod httpGet = null;
    Bitmap bitmap = null;

    try {
      httpClient = getHttpClient();
      httpGet = getHttpGet(url, null, null);
      if (httpClient.executeMethod(httpGet) == HttpStatus.SC_OK) {
        InputStream inStream = httpGet.getResponseBodyAsStream();
        bitmap = BitmapFactory.decodeStream(inStream);
        inStream.close();

        mImageView03.setImageBitmap(bitmap);
      }
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpGet.releaseConnection();
      httpClient = null;
    }
  }
예제 #15
0
  public static String postXml(String url, String xml) {
    String txt = null;
    PostMethod post = new PostMethod(url); // 请求地址
    post.setRequestBody(xml); // 这里添加xml字符串

    // 指定请求内容的类型
    post.setRequestHeader("Content-type", "text/xml; charset=iso-8859-1");
    HttpClient httpclient = new HttpClient(); // 创建 HttpClient 的实例
    int result;
    try {
      result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result); // 返回200为成功
      System.out.println("Response body: ");

      BufferedReader reader =
          new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), "ISO-8859-1"));
      String tmp = null;
      String htmlRet = "";
      while ((tmp = reader.readLine()) != null) {
        htmlRet += tmp + "\r\n";
      }
      txt = new String(htmlRet.getBytes("ISO-8859-1"), "UTF-8");
      System.out.println(txt);

      // txt = post.getResponseBodyAsString();
      // System.out.println(post.getResponseBodyAsString());// 返回的内容
      post.releaseConnection(); // 释放连接
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return txt;
  }
예제 #16
0
  public Map<String, String> read(String in) {
    List<String> result = new ArrayList<String>();
    HttpClient client = new HttpClient();
    //	client.getHostConfiguration().setProxy("wwwcache.open.ac.uk", 80);
    ModelFactory modelFactory = RDF2Go.getModelFactory();
    Model model = modelFactory.createModel();

    String serviceEndPoint = "http://ws.geonames.org/search?q=" + "London" + "&type=rdf";

    GetMethod geoNameSearch = new GetMethod(serviceEndPoint);

    String rdf = "";
    try {
      client.executeMethod(geoNameSearch);
      rdf = geoNameSearch.getResponseBodyAsString();
      String rdf8 = new String(rdf.getBytes(), "UTF-8");

      System.out.println(rdf8);

      String modelQueryString =
          "SELECT DISTINCT ?name ?country ?location ?map ?lat ?long WHERE { ?location <http://www.geonames.org/ontology#name> ?name ."
              + "?location <http://www.geonames.org/ontology#locationMap> ?map ."
              + "?location <http://www.geonames.org/ontology#countryCode> ?country ."
              + "?location <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?lat ."
              + "?location <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?long}";

      model.open();

      model.readFrom(new ByteArrayInputStream(rdf8.getBytes()));

      QueryResultTable results = model.sparqlSelect(modelQueryString);
      System.out.println(results.toString());
      ClosableIterator<QueryRow> iter = results.iterator();
      while (iter.hasNext()) {
        QueryRow row = iter.next();
        String name = row.getValue("name").toString();
        String country = row.getValue("country").toString();
        String location = row.getValue("location").toString();
        String map = row.getValue("location").toString();
        String lat = row.getValue("lat").toString();
        String longatti = row.getValue("long").toString();
        result.add(
            name + " -> " + country + ";" + location + ";" + lat + ";" + longatti + ";" + name + ";"
                + name + ":" + country + ":" + location + ":" + map);
      }

    } catch (HttpException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    model.close();
    //	return result;
    return null;
  }
예제 #17
0
 /**
  * 获取网络图片
  *
  * @param url
  * @return
  */
 public static Bitmap getBitmapByNet(String url) throws AppException {
   // System.out.println("image_url==> "+url);
   URI uri = null;
   try {
     uri = new URI(url, false, "UTF-8");
   } catch (URIException e) {
     e.printStackTrace();
   }
   if (uri != null) url = uri.toString();
   HttpClient httpClient = null;
   GetMethod httpGet = null;
   Bitmap bitmap = null;
   int time = 0;
   do {
     try {
       httpClient = HttpHelper.getHttpClient();
       httpGet = HttpHelper.getHttpGet(url, HttpHelper.getUserAgent());
       int statusCode = httpClient.executeMethod(httpGet);
       if (statusCode != HttpStatus.SC_OK) {
         throw AppException.http(statusCode);
       }
       InputStream inStream = httpGet.getResponseBodyAsStream();
       bitmap = BitmapFactory.decodeStream(inStream);
       inStream.close();
       break;
     } catch (HttpException e) {
       time++;
       if (time < RETRY_TIME) {
         try {
           Thread.sleep(1000);
         } catch (InterruptedException e1) {
         }
         continue;
       }
       // 发生致命的异常,可能是协议不对或者返回的内容有问题
       e.printStackTrace();
       throw AppException.http(e);
     } catch (IOException e) {
       time++;
       if (time < RETRY_TIME) {
         try {
           Thread.sleep(1000);
         } catch (InterruptedException e1) {
         }
         continue;
       }
       // 发生网络异常
       e.printStackTrace();
       throw AppException.network(e);
     } finally {
       // 释放连接
       httpGet.releaseConnection();
     }
   } while (time < RETRY_TIME);
   return bitmap;
 }
예제 #18
0
  public static void main(String[] args) {
    // (1)构造HttpClient的实例
    HttpClient httpClient = new HttpClient();

    // (2)创建POST方法的实例
    PostMethod postMethod =
        new PostMethod("http://10.3.75.203:9080/ESB/appleServie?serviceCode=authentication");
    //		 GetMethod getMethod = new GetMethod("http://*****:*****@apple.com\",\"password\": \"Apple1234\", \"shipTo\":\"863348\",\"langCode\":\"en\",\"timeZone\":\"420\"}";
    postMethod.setRequestHeader("http.default-headers", authenticateText);
    // 使用系统提供的默认的恢复策略
    postMethod
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    try {
      postMethod.setRequestEntity(
          new StringRequestEntity(authenticateText, "text/xml; charset=UTF-8", "UTF-8"));
      // (4)执行postMethod
      int statusCode = httpClient.executeMethod(postMethod);
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + postMethod.getStatusLine());
      }

      // (5)读取response头信息
      //			Header headerResponse = postMethod
      //					.getResponseHeader("response_key");
      //			String headerStr = headerResponse.getValue();
      // (6)读取内容
      byte[] responseBody = postMethod.getResponseBody();
      // (7) 处理内容
      //			System.out.println(headerStr);
      System.out.println("返回的内容信息:" + new String(responseBody, "UTF-8"));
    } catch (HttpException e) {
      // 发生致命的异常,可能是协议不对或者返回的内容有问题
      System.out.println("Please check your provided http address!");
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // 释放连接
      postMethod.releaseConnection();
    }
  }
예제 #19
0
 /**
  * 获取用户的主页
  *
  * @param client
  * @param homePageUrl
  * @throws IOException
  */
 public static void getHomePage(HttpClient client, String homePageUrl) throws IOException {
   // TODO Auto-generated method stub
   GetMethod get = new GetMethod(homePageUrl);
   try {
     client.executeMethod(get);
   } catch (HttpException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   String response = get.getResponseBodyAsString();
   System.out.println(response);
 }
예제 #20
0
 //	 @Scheduled(cron = "1 0/5 * * * *")
 private void refreshCookie() {
   resetMethod();
   try {
     httpMethod.setPath("/");
     httpClient.executeMethod(httpMethod);
   } catch (HttpException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  @org.junit.Test
  public void test_crossdomain_url() {

    HttpMethod get = new GetMethod(SLING_URL + CROSSDOMAIN_URL);
    try {
      client.executeMethod(get);
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    assertTrue((get.getStatusCode() != 403));
  }
예제 #22
0
 public static String HttpPost(String url, String method, Map parmMap) throws Exception {
   String encoding = "UTF-8";
   String webUrl = url + "/" + method;
   if (encoding == null || "".equals(encoding)) encoding = "UTF-8";
   StringBuffer sBuffer = new StringBuffer();
   // 构造HttpClient的实例
   HttpClient httpClient = new HttpClient();
   // 创建POS方法的实例
   NameValuePair[] pairs = null;
   PostMethod postMethod = new PostMethod(webUrl);
   if (parmMap != null) {
     pairs = new NameValuePair[parmMap.size()];
     Set set = parmMap.keySet();
     Iterator it = set.iterator();
     int i = 0;
     while (it.hasNext()) {
       Object key = it.next();
       Object value = parmMap.get(key);
       pairs[i] = new NameValuePair(key.toString(), value.toString());
       i++;
     }
     postMethod.setRequestBody(pairs);
   }
   postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
   try {
     // 执行getMethod
     int statusCode = httpClient.executeMethod(postMethod);
     if (statusCode != HttpStatus.SC_OK) {
       System.err.println("Method failed: " + postMethod.getStatusLine());
     }
     InputStream resStream = postMethod.getResponseBodyAsStream();
     sBuffer = new StringBuffer(postMethod.getResponseBodyAsString() + "");
     // modify by guanshiqiang at 2012-06-01 for 处理接收字符乱码bug end
     // 处理内容
     // sBuffer.append(new String(responseBody,encoding));
   } catch (HttpException e) {
     // 发生致命的异常,可能是协议不对或者返回的内容有问题
     System.out.println("Please check your provided http address!");
     e.printStackTrace();
     throw e;
   } catch (IOException e) {
     e.printStackTrace();
     throw e;
   } finally {
     // 释放连接
     postMethod.releaseConnection();
   }
   return sBuffer.toString();
 }
예제 #23
0
  public static String get(String url) {
    HttpMethod method = new GetMethod(url);
    try {
      int returnCode = client.executeMethod(method);
      if ((returnCode >= 200) && (returnCode < 300)) {
        return method.getResponseBodyAsString();
      }
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
예제 #24
0
  public static String HttpPostForLogistics(String url, String method, String str) {
    String encoding = "UTF-8";
    String webUrl = url + "/" + method;
    StringBuffer sBuffer = new StringBuffer();
    // 构造HttpClient的实例
    HttpClient httpClient = new HttpClient();
    // 创建POS方法的实例
    PostMethod postMethod = new PostMethod(webUrl);
    try {
      // postMethod.setRequestEntity(new ByteArrayRequestEntity(str.getBytes(),"application/json;
      // charset=utf-8"));
      postMethod.setRequestBody(str);
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000); // 连接5秒超时
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000); // 读取30秒超时
    // postMethod.setRequestHeader("Content-type", "application/json; charset=utf-8");
    // postMethod.setDoAuthentication(false);
    // postMethod.addRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT
    // 5.1)");

    postMethod.setDoAuthentication(true);
    postMethod.addRequestHeader("Authorization", "Basic U0FQX0FNOkFubmllTWFvMTIzNA==");
    postMethod.setRequestHeader("Content-type", "application/json");
    try {
      // 执行getMethod
      int statusCode = httpClient.executeMethod(postMethod);
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + postMethod.getStatusLine());
        sBuffer = new StringBuffer();
      } else {
        sBuffer = new StringBuffer(postMethod.getResponseBodyAsString() + "");
      }
    } catch (HttpException e) {
      // 发生致命的异常,可能是协议不对或者返回的内容有问题
      System.out.println("Please check your provided http address!");
      e.printStackTrace();
    } catch (IOException e) {
      // 发生网络异常
      e.printStackTrace();
    } finally {
      // 释放连接
      postMethod.releaseConnection();
    }
    return sBuffer.toString();
  }
예제 #25
0
  public Optional<String> makeRequest(String url, String parameterString) {

    final org.apache.commons.httpclient.HttpClient httpClient =
        new org.apache.commons.httpclient.HttpClient(connectionManager);
    GetMethod getMethod = new GetMethod(url + parameterString);
    try {
      httpClient.executeMethod(getMethod);
      return Optional.of(getMethod.getResponseBodyAsString());
    } catch (HttpException e) {
      e.printStackTrace();
      return Optional.empty();
    } catch (IOException e) {
      e.printStackTrace();
      return Optional.empty();
    }
  }
  /* 下载 url 指向的网页 */
  public String downloadFile(String url) {
    String filePath = null;
    /* 1.生成 HttpClinet 对象并设置参数 */
    HttpClient httpClient = new HttpClient();
    // 设置 Http 连接超时 5s
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    /* 2.生成 GetMethod 对象并设置参数 */
    GetMethod getMethod = new GetMethod(url);
    // 设置 get 请求超时 5s
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    // 设置请求重试处理
    getMethod
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    /* 3.执行 HTTP GET 请求 */
    try {
      int statusCode = httpClient.executeMethod(getMethod);
      // 判断访问的状态码
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + getMethod.getStatusLine());
        filePath = null;
      }

      /* 4.处理 HTTP 响应内容 */
      byte[] responseBody = getMethod.getResponseBody(); // 读取为字节数组
      // 根据网页 url 生成保存时的文件名
      filePath =
          "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
      // createFile(filePath);
      FileUtils.createFile(filePath);
      saveToLocal(responseBody, filePath, false);
    } catch (HttpException e) {
      // 发生致命的异常,可能是协议不对或者返回的内容有问题
      System.out.println("Please check your provided http address!");
      e.printStackTrace();
    } catch (IOException e) {
      // 发生网络异常
      e.printStackTrace();
    } finally {
      // 释放连接
      getMethod.releaseConnection();
    }
    return filePath;
  }
예제 #27
0
 // ���� URL ָ�����ҳ
 public String downloadFile(String url) {
   String filePath = null;
   // 1.���� HttpClinet��������
   HttpClient httpClient = new HttpClient();
   // ���� HTTP���ӳ�ʱ 5s
   httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
   // 2.���� GetMethod��������
   GetMethod getMethod = new GetMethod(url);
   // ���� get����ʱ 5s
   getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
   // �����������Դ���
   getMethod
       .getParams()
       .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
   // 3.ִ��GET����
   try {
     int statusCode = httpClient.executeMethod(getMethod);
     // �жϷ��ʵ�״̬��
     if (statusCode != HttpStatus.SC_OK) {
       System.err.println("Method failed: " + getMethod.getStatusLine());
       filePath = null;
     }
     // 4.���� HTTP ��Ӧ����
     byte[] responseBody = getMethod.getResponseBody(); // ��ȡΪ�ֽ�����
     // ������ҳ url ���ɱ���ʱ���ļ���
     filePath =
         "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
     File file = new File(filePath);
     if (!file.getParentFile().exists()) {
       file.getParentFile().mkdir();
     }
     saveToLocal(responseBody, filePath);
   } catch (HttpException e) {
     // �����������쳣��������Э�鲻�Ի��߷��ص�����������
     System.out.println("�������http��ַ�Ƿ���ȷ");
     e.printStackTrace();
   } catch (IOException e) {
     // ���������쳣
     e.printStackTrace();
   } finally {
     // �ͷ�����
     getMethod.releaseConnection();
   }
   return filePath;
 }
예제 #28
0
 /**
  * Validates login on Gitlab.
  *
  * @param username
  * @param token
  * @return true if username & token are valid, false otherwise.
  */
 public static boolean validateLogin(final String url, final String token) {
   try {
     String string = url + API + "/projects?private_token=" + token;
     int result = new HttpClient().executeMethod(new GetMethod(string));
     if (result == 200) {
       return true;
     }
   } catch (HttpException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     return false;
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     return false;
   }
   return false;
 }
 public static String getGetResponse(String url) {
   String html = "";
   GetMethod getMethod = new GetMethod(url);
   try {
     int statusCode = httpClient.executeMethod(getMethod);
     if (statusCode != HttpStatus.SC_OK) {
       System.err.println("Method failed: " + getMethod.getStatusLine());
     }
     html = getMethod.getResponseBodyAsString();
   } catch (HttpException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     getMethod.releaseConnection();
   }
   return html;
 }
  public static void executeHttpGet() throws Exception {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    method.addRequestHeader("command", "addCredit");
    //	    method.addRequestHeader("value", "addCredit");

    // Provide custom retry handler is necessary
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();
      System.out.println(responseBody);
      System.out.println(method.getResponseHeader("response"));

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }
  }