zoukankan      html  css  js  c++  java
  • convert curl command into java HttpGet

    如何把命令 

    curl -k -X GET -H "Accept: Application/json" -H "Content-Type: application/json" -u username:password https://someURL/api/cusa/customer/v1/85267198615 

    转换为 java 程序发送 ? 

    --------------------------------------------------

    红色部分为关键代码 

    先用 url 构造一个 HttpGet ,  然后加两个 header , 注意大小写, username 和 password 要用蓝字部分的代码加到 header 里面 

    --------------------------------------------------

    参考文章

    https://stackoverflow.com/questions/19797601/apache-http-basicscheme-authenticate-deprecated

    search 关键字 

    addHeader(BasicScheme.authenticate

    java httpget authen

    java httpget set parameters

        public String authenticate(String strRequest) {
    
            CloseableHttpResponse httpResponse = null;
            CloseableHttpClient httpClient = null;
            JSONObject requestJson = null;
    
            try {
    
                requestJson = new JSONObject(strRequest);
    
                if (Utility.validateMsisdn(requestJson.getString("b_party")) == false) {
                    requestJson.put("status", ServiceAuthentication.Incomplete_Msisdn);
                    return requestJson.toString();
                }
    
                PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
                cm.setMaxTotal(200);
                cm.setDefaultMaxPerRoute(20);
    
                RequestConfig defaultRequestConfig = RequestConfig.custom()
                        .setSocketTimeout(Configuration.get("service.timeout.socket", 20000))
                        .setConnectTimeout(Configuration.get("service.timeout.connect", 20000))
                        .setConnectionRequestTimeout(Configuration.get("service.timeout.connectrequest", 20000)).build();
    
                JSONObject responseJson = new JSONObject();
                ContentBasedRetryStrategy retryStrategy = new ContentBasedRetryStrategy();
                httpClient = HttpClients.custom().setServiceUnavailableRetryStrategy(retryStrategy)
                        .setDefaultRequestConfig(defaultRequestConfig).setConnectionManager(cm).build();
           //*************************重要
                HttpGet request = new HttpGet(
                        Configuration.get("service.authentication.url", "") + requestJson.getString("b_party"));
                request.addHeader("Content-type", "application/json");
                request.addHeader("Accept", "application/json");
    
                UsernamePasswordCredentials creds = new UsernamePasswordCredentials(Configuration.get("service.username", ""),Configuration.get("service.password", ""));
    
                Header header = new BasicScheme(StandardCharsets.UTF_8).authenticate(creds , request, null);
                request.addHeader( header); 
                //************************************
                
        
                this.logger.info(String.format(Configuration.get("service.authentication.url", "") + requestJson.getString("b_party")));
                
                Header [] headers = request.getAllHeaders();
                for (int i = 0;i < headers.length; i++ ) {
                    Header tmp = headers[i];
                    this.logger.info(String.format("Headers Name: %s Value:%s
    ", tmp.getName(), tmp.getValue()));
                }
                
                
                //////////////////  temp
                
    //            JSONObject subscriberProfileNode = new JSONObject();
    //            
    //            subscriberProfileNode.put("type", 8);
    //            subscriberProfileNode.put("is_allowed", true);
    //            requestJson.getJSONObject("function").put("subscriber_profile", subscriberProfileNode);
    //            
    //            requestJson.put("status", ServiceAuthentication.Success);
    //            
    //            JSONObject operatorProfileNode = new JSONObject();
    //            operatorProfileNode.put("operator", "hkg.csl");
    //            requestJson.getJSONObject("function").put("operator_profile", operatorProfileNode);
    //            
    //            return requestJson.toString();
                
                
                //////////////////// end temp 
                
                
                httpResponse = httpClient.execute(request);
    
                responseJson = retryStrategy.getResponseObject();
                this.logger.info(String.format("HTTP Response: %d, Body: %s", httpResponse.getStatusLine().getStatusCode(),
                        responseJson.toString()));
    
                if (responseJson != null) {
                    if (responseJson.getJSONObject("status") != null
                            && responseJson.getJSONObject("status").getInt("code") == 0) {
    
                        int subType = 99;
    
                        subType = responseJson.getJSONObject("profile").getInt("brand");
    
                        JSONObject subscriberProfileNode = new JSONObject();
                        subscriberProfileNode.put("type", subType);
                        subscriberProfileNode.put("is_allowed", subType == 8 ? true : false);
    
                        boolean bSaved = true;
    
                        if (bSaved) {
                            if (subType != 8) {
                                requestJson.put("status", ServiceAuthentication.Subscriber_Is_Postpaid);
                            } else {
                                requestJson.put("status", ServiceAuthentication.Success);
                            }
                        }
    
                        requestJson.getJSONObject("function").put("subscriber_profile", subscriberProfileNode);
    
                        JSONObject operatorProfileNode = new JSONObject();
                        operatorProfileNode.put("operator", "hk.csl");
                        requestJson.getJSONObject("function").put("operator_profile", operatorProfileNode);
    
                    } else if (responseJson.getJSONObject("status") != null
                            && responseJson.getJSONObject("status").getInt("code") == 1002) {
                        JSONObject operatorProfileNode = new JSONObject();
                        operatorProfileNode.put("operator", "hk.csl");
                        requestJson.getJSONObject("function").put("operator_profile", operatorProfileNode);
    
                        requestJson.put("status", ServiceAuthentication.Subscriber_Not_Found);
                    }
    
                    return requestJson.toString();
                }            
    
            } catch (Exception e) {
                logger.error("Failed to complete ServiceAuthen request: " + e.getMessage(), e);
            } finally {
                try {
                    httpClient.close();
                } catch (Exception e) {
                }
            }
    
            return getSubcriberInfoFromCache(requestJson, requestJson.getString("b_party"));
        }
    
        private String getSubcriberInfoFromCache(JSONObject requestJson, String msisdn) {
            return "";
        }
    }
  • 相关阅读:
    1300 · 巴什博弈
    1 · A + B 问题
    37 · 反转一个3位整数
    145 · 大小写转换
    Spring-Boot整合freemarker引入静态资源css、js等
    Monkey API学习与脚本编写小记
    Mac终端快速启动uiautomatorviewer
    Mac解决使用uiautomatorviewer会报错:./uiautomatorviewer 03:56:07 E/Screenshot: Unsupported protocol: 2
    charles抓包https乱码问题解决-转载
    mac解决adb devices命令找不到真机设备
  • 原文地址:https://www.cnblogs.com/lthxk-yl/p/8080548.html
Copyright © 2011-2022 走看看