/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.codahale.gprcproxy;

import io.grpc.stub.ServerCalls.UnaryMethod;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Proxies a gRPC request to an HTTP backend.
 */
class ProxyUnaryMethod implements UnaryMethod<byte[], byte[]> {

  private static final MediaType OCTET_STREAM = MediaType.parse("application/octet-stream");
  private final OkHttpClient client;
  private final HttpUrl backend;
  private final String methodName;

  ProxyUnaryMethod(OkHttpClient client, HttpUrl backend, String methodName) {
    this.client = client;
    this.backend = backend;
    this.methodName = methodName;
  }

  @Override
  public void invoke(byte[] msg, StreamObserver<byte[]> responseObserver) {
    final HttpUrl url = backend.newBuilder().addQueryParameter("method", methodName).build();
    final RequestBody body = RequestBody.create(OCTET_STREAM, msg);
    final Request req = new Request.Builder().url(url).post(body).build();
    try {
      try (Response response = client.newCall(req).execute()) {
        responseObserver.onNext(response.body().bytes());
      }
      responseObserver.onCompleted();
    } catch (IOException e) {
      responseObserver.onError(e);
    }
  }
}

@@ -1133,50 +1133,11 @@
 Url 
-backend;%0A  private final String methodName
+url
 ;%0A%0A 
@@ -1248,23 +1248,19 @@
    this.
-backend
+url
  = backe
@@ -1265,31 +1265,49 @@
 kend
-;%0A    this.methodName =
+.newBuilder().addQueryParameter(%22method%22,
  met
@@ -1313,16 +1313,25 @@
 thodName
+).build()
 ;%0A  %7D%0A%0A 
@@ -1431,121 +1431,104 @@
 nal 
-HttpUrl url = backend.newBuilder().addQueryParameter(%22method%22, methodName).build();%0A    final RequestBody body = 
+Request req = new Request.Builder().url(url)%0A                                             .post(
 Requ
@@ -1564,75 +1564,55 @@
 msg)
-;
+)
 %0A    
-final Request req = new Request.Builder().url(url).post(body)
+                                         
 .bui

Build the method URL once.